Posts From Category: Javascript

Window.postMessage part 2 - an example

In Part 1 of the series, I talked about the basics of Window.postMessage and showed some sample code.  This post will show some real code with a demo link.   This code purposefully has some security issues which will be addressed in the third and final post of the series.

The demo code found at is –

`<iframe src="" style="width:100%; height:50%;"></iframe>


What it does is load in an iframe that is 50% of the height of the window and 100% of the width.  It then has a form where you can specify text and when you hit submit, it sends a message to the iframe with the text that is specified in the form.

The code for is –`


It first creates registers a function(receiveMessage) to handle the “message” event and creates a div.  When a message is received it, it  appends the text to the div.

Read More

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.

Read More