Window.postMessage part 1 – the basics

What is Window.postMessage?
Window.postMessage is a way to safely communicate cross-origin between windows. Normally, pages are only allowed to interact with each other if they share the same origin(protocol+host+port matching). postMessage allows the a developer to get around that.


targetWindow.postMessage(message, targetOrigin, [transfer]);

The components are-

      • targetWindow – a reference to another window that you wish to send a message to. You can obtain a reference by a) the object returned by, b) the contentWindow of an iframe, and c) using the numeric index on the Window.frames object
      • message – data sent to the window
      • targetOrigin – specify what the origin of targetWindow must be in order for the event to be dispatched. Either ‘*’ or the full origin. This is necessary because the origin of the window may have changed. It is advised not to specify ‘*’, otherwise you may be sending data to an unintended origin.
      • transfer (optional) – objects that are transferred with the message. After transferring, they are no longer accessible by the sender

What does it look like in practice?
The code in the target window ( would look something like this. This script lives on the default page for

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
  var origin = event.origin || event.originalEvent.origin; // For Chrome,
  if (origin !== "")

The above code is based off of

This is what the sending code would look like (on

var wnd =";
wnd.postMessage("Test Message", "");

That’s basically what it looks like and how you use Window.postMessage to send messages cross-origin. This gets around the same origin policy which restricts how windows can interact with each based on having the same protocol, host, and port. Part 2 of the series will continue the discussion with the security implications of Window.postMessage and how using it improperly can lead to unintended security vulnerabilities in a page.

This entry was posted in Javascript, Security. Bookmark the permalink.