Cross Origin Communication – window.postMessage


Read {count} times since 2020

The Window.postMessage helps to make scripts talk over different domain connections. When you call a function on an external iframe from the parent window, Javascript won’t allow it.
That’s because of the Cross Domain Policy that makes this not possible. But it’s possible since Javascript introduced postMessage function.

Suppose you want to call a function on an cross domain iframe with id monu. Let the function be subins(). Here’s how to do it using postMessage technic.

window.frames[‘monu’].postMessage(‘alert’,’*’);

The alert in the code above is not a function. The parameter targetOrigin is set to * because we don’t know the url of the iframe. Now the code in the iframe :

function subins(){
 alert("Support Wikipedia");
}
window.addEventListener("message",function(e){
 if(e.origin==’http://example.com’){
  subins();
 }
},false);

When a postmessage callback is received on the iframe the origin where the postMessage callback is called is checked on the script in iframe and if it is true, subins() is called and it will alert the text Support Wikipedia.
So now you know how to communicate between cross domains. Code Great.

Show Comments