Cross Domain Communication using postMessage

In this article I am going to explain how to communicate between a page and a popup or a page and an embedded iframe.

Due to cross domain security measures communication between two different origin protocol sites are restricted. Communication is only possible when the two pages belongs to same origin protocol.

Buy by using postMessage it’s possible to communicate safely between a page and a popup or a page and an iframe.

Let’s discuss how to use postMessage for cross domain communication.

It’s easy to send postMessage but the receiver window must have an event listener registered to receive post messages.

Syntax to send message is


targetWindow.postMessage(message, targetOrigin);

Example


top.postMessage('hello', 'A');
parent.postMessage({'message': 'Hello World'}, 'A');

To add an event listener, check below code.


window.addEventListener( "message",
          function (e) {
                if(e.origin !== 'B'){ return; } 
                alert(e.data);
          },
          false);
window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
  if (event.origin !== "http://domain.com")
    return;

  // ...
}

Hope this helps.

Share this Post