How to execute code from an iFrame to the parent page

I recently came across a unique situation where I had to execute code from the child iframe on the parent page.  The problem was that the iframe was calling a page from another domain.  A few years ago, this would have been easy to implement because all browsers allows cross site scripts to execute code; however, this was huge security problem.  Hackers could execute code on a remote website and steal peoples information so they blocked cross site script execution.

The only way around this is to use the Cross Document Messaging API.  This api uses the publisher-subscriber design pattern.

The first step is setting up the parent page that has the code you wish to execute from the child page:

Below is the code to place onto the parent page:

<script>
var eventMethod = window.addEventListener ? “addEventListener” :“attachEvent”;
var eventer = window[eventMethod];
var messageEvent = eventMethod == “attachEvent” ? “onmessage” :“message”;

// Listen to message from child window
eventer(messageEvent,function(e) {
if(e.data == “changeParentBackgroundToBlue”)
{
document.body.style.backgroundColor = “blue”;
}
},false);
//This will allow you to change the background color of the child page
window.document.getElementById(“myIFrame”).contentWindow.postMessage(“changeChildBackgroundToRed”,“*”);
/*postMessage second parameter represents the domain name to which this message can be sent to, if the child domain name doesn’t match then this message will not be sent. Here * means any domain */
</script>

The second step is to call the method from the Child page:

<script>

//The sets up the event listener on the client page.

var eventMethod = window.addEventListener ? “addEventListener” :“attachEvent”;
var eventer = window[eventMethod];
var messageEvent = eventMethod == “attachEvent” ? “onmessage” :“message”;

// Listen to message from child window
eventer(messageEvent,function(e) {
if(e.data == “changeChildBackgroundToRed”)
{
document.body.style.backgroundColor = “red”;
}
},false);
//This is the code that call the parent page function
window.parent.postMessage(“changeParentBackgroundToBlue”,“*”);

</script>

 

Leave a Reply

Your email address will not be published. Required fields are marked *