Cross-Domain IFrame using HTML5

 
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 I’m using 2 html pages(parent.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:

parent.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>

Thats all. Now it will work perfectly.
Enjoy the coding!!!

Muneeswaran
Latest posts by Muneeswaran (see all)