Ikodes Technology

Cross-Domain IFrame using HTML5
Generally, web application allows script running between pages(parent and iframe pages) in the same domain based on same-origin-policy. Unfortunately it does not support scripts if different domain. The policy does not allow it.
But still one another way in HTML5 using “PostMessage”.

Yes.. postMessage is playing vital role to communicate between windows(parent/iframe) by sending message.

Here we can see how to communicate between windows by the following simple steps.

**Notes: Here we are using 2 html pages(index.html and iframe.html), one for parent window and another one is for iframe. Both can be in same domain or in different domain. Here we assume both pages are in diffirent domains.
The subject is to hide the iframe by clicking close button inside the iframe.
Basically, for same domain, the “window.parent” or “window.top” will work very fine. But for different domain, they does not. So the following steps will be helpful to solve it.

Step 1:
iframe.html, it has a close button, when click it, it sends message to parent window to hide the iframe.
<!DOCTYPE html>
<html lang="en">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script type="text/javascript">
function closeme(){
window.top.postMessage('closeme', '*');
}
</script>
</head>
<body>
<h1>I am child...</h1>
<button type="button" onclick="closeme()">Close Me</button>
</body>
</html>

Step 2:
index.html, it is needed to receive message from iframe postmessage, and using that message we can run the script to hide it.

**Notes: So on window load, we need to add listener to receive message by using “addEventListener”. And then once received, it will process it by using “receiveMessage”

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script type="text/javascript">
function initme(){
window.addEventListener('message', receiveMessage, false);
}
function receiveMessage(event){
if(event.data=="closeme"){
document.getElementById("ifrm").style.display = "none";
}
}
window.onload = initme;
</script>
</head>
<body>
<h1>I am parent...</h1>
<iframe id="ifrm" src="iframe.html" style="width:500px;height:300px;"></iframe>
</body>
</html>

 



Author Bio

ikodes Technology

Manager of Marketing for Red Stag Fulfillment, an ecommerce fulfillment warehouse that was born out of ecommerce. He has years of experience in ecommerce and business development. In his free time, Jake enjoys reading about business and sharing his own experience with others.

Go Back

Expand Your Digital Horizons With Us

Start a new project or take an existing one to the next level. Get in touch to start
small, scale-up, and go Agile.

    Math Captcha − 2 = 1

    Leave a Reply