23 May 2013

Think of cross window, cross iframe communication and what comes to mind is postMessage API. This postMessage api allows windows(iframes) to communicate among themselves.

One window can post a message to other message and the other can react to the message upon recieving it. Lets see how it works.


Code in Message Sender window

var window2=window.open("/someurl.html"); 

/* This url can be anything but it should point to page which is the reciever */

window2.postMessage("Hello window 2","http://devangpaliwal.com");


Explanation

The code above is trying to send message Hello window 2 to window2 whose domain must be devangpaliwal.com



Code in Reciever window

/* This code is present in someurl.html */
    
if(!window.attachEvent){
    window.addEventListener("message",function(e){
        console.log("Recieved ",e.data);
    }); 
}else{
    window.attachEvent("message",function(){
        console.log("Recieved ",e.data);
    }); 
}


Explanation

The code above sits in the receiver window and listens to message event. Whenever it gets the message event it prints out a log message in the console.


Caution

If you do not expect to receive messages from other sites, do not add any event listeners for message events.

On the recieving end we should check for the domain from which we get the message. Failing to check that can lead to cross-site scripting attacks. We should also check the syntax of the message recieved.

if(e.origin == "devangpaliwal.com"){
  console.log("I accept the message as it is recieved from devangpaliwal.com");
}


Browser Support

IE8+, FF, Chrome, Opera and Safari


Demo


More Information



blog comments powered by Disqus