Cross-Domain IFrame Communication using HTML5

The same-origin-policy is an important concept in the web application security model.The policy permits scripts running on pages originating from the same site — a combination of scheme, hostname, and port number to access each other’s DOM no specific restrictions, but prevents access to DOM on different sites. Source — Wikipedia

As a developer we have at some point faced the Cross Domain Access issue while building web applications.We encounter these issues whenever the application wants to make the calls from the browser itself to a page hosted in different domain say for example, http://www.example.com/appPage.html wants to make a call to a page or service hosted in domain http://www.iframe.com/iframe.html. By default as a security constraint the browser block this type of communication to disallow the malicious applications to fetch the data or execute the code without the users permission.

But the “postmessage” functun of HTML5 provide this remarkable solution for solving this.

For demonstration we will take one parent.html and i-frame.html file and try to access the iframe.html from parent.html.

Here is our parent.html page:

<html>
<head>
<script type="text/javascript">
window.addEventListener('message', receiveMessage, false);
function receiveMessage(event) {
alert("got message: " + event.data);
}
</script>
</head>
<title> Parent Page </title>
<body>
<iframe src="http://path.com/Iframe.html" width="500" height="500"></iframe>
</body>
</html>

This will run the iframe and the window.addEventListener take care of the postmessage call from iframe.html.

Now below is our Iframe.html page

<html>
<head>
<script>
function send() {
window.parent.postMessage('Hello Parent Frame!', '*');
}
</script>
</head>
<title> IFrame Test </title>
<body>
<h1> Welcome </h1>
<p> Hello There </body>
<button onclick="send()">Send</button>
</body>
</html>

This will call the window.parent.postMessage() function after the instantiation of click event by the user and send the message ‘Hello Parent Frame!’ to the parent page.

Run the parent.html and click on the send button the parent page will receive the message ‘Hello Parent Frame!’ in alert box.

This way we can simply initiate the communication using HTML5 itself without any king of third party framework.

Do share your thoughts for the same.

Happy Learning!!!