We are working on a new version of Javascript.info with updated content and design.

Cross-window messaging with postMessage

  1. Example
  2. The receiving side
  3. Nifty details
  4. Summary

Cross-window messaging API is supported by all modern browsers including IE8. It allows windows/frames from multiple domains to communicate with each other.

To send a message to another window referenced by win, the postMessage method is used.

Syntax is postMessage(data, targetDomain), where:

The message. Accordin to the specification, it could be any object. But as of now, only strings are supported in major browsers.
Limit receiving iframe by given domain. Can contain ‘*’ which doesn’t put any restrictions.

Usually, the domain of iframe is known, so it is recommended to pass it as the targetDomain argument for better security.


Let’s see how it works from the sending side.

<iframe src="http://a.JavaScript.info/files/tutorial/window/receive.html" id="iframe" style="height:60px"></iframe>

<form name="form">
  <input type="text" name="msg" value="Your message"/>
  <input type="submit"/>


  var win = document.getElementById("iframe").contentWindow

  document.forms.form.onsubmit = function() {
    return false


By pressing the button, you send the message to iframe on another domain. The browser controls that the domain must be a.JavaScript.info (targetDomain).

The receiving side

The receiving side hooks on a message event. The source of the iframe, used in the example above:

<div id="test">Send me a message!</div>
function listener(event){
  if ( event.origin !== "http://javascript.info" )

  document.getElementById("test").innerHTML = "received: "+event.data

if (window.addEventListener){
  addEventListener("message", listener, false)
} else {
  attachEvent("onmessage", listener)

Note that the browser guarantees that event.origin contains the real domain which sent the message. There is no way for JavaScript hacker to replace it.

Usually you’d want to filter who may send messages/commands to iframe and who may not.

Cross-window messaging security model is two-sided. The sender ensures that the receiving domain is targetDomain. The receiver checks that the message came from proper event.origin.

The special propertys of a message event are:

The first argument of postMessage
The source domain
The reference to sending window. It is possible to respond by calling event.source.postMessage('..response message..', event.origin).

Nifty details

The messages are passed using internal browser API. So there is no network communication at all.

In IE8, it is possible to use win.postMessage for iframes only, not for other tabs/windows. That’s the bug of implementation. Other browsers don’t suffer from that.


The postMessage API allows to communicate between windows in a safe, cross-browser way.

Works in all madern major browsers including Chrome/Safari, Firefox, Opera and IE8.

IE8 doesn’t allow to postMessage to other windows, only to iframes.