Site icon Freelance Web Developer, Web Designer Mumbai India

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);


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; } 
window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
  if (event.origin !== "")

  // ...

Hope this helps.

Exit mobile version