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.
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.
By pressing the button, you send the message to iframe on another domain. The browser controls that the domain must be
The receiving side
The receiving side hooks on a
message event. The source of the
iframe, used in the example above:
Note that the browser guarantees that
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
The special propertys of a message event are:
- The first argument of
- The source domain
- The reference to sending window. It is possible to respond by calling
event.source.postMessage('..response message..', event.origin).
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.
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.