Cross-Origin Messaging

As noted in Multiple Windows and Frames, some browser windows and tabs are completely isolated from each other, and the code running in one is completely unaware of the others. In other cases, when a script explicitly opens new windows or works with nested frames, the multiple windows and frames are aware of each other. If they contain documents from the same web server, scripts in these windows and frames can interact with each other and manipulate each other’s documents.

Sometimes, however, a script can refer to another Window object, but because the content in that window is from a different origin, the web browser (following the same-origin policy) will not allow the script to see the document content of that other window. For the most part, the browser won’t allow the script to read properties or invoke methods of that other window, either. One window method that scripts from different origins are allowed to invoke is called postMessage(), and this method enables a limited kind of communication—in the form of asynchronous message passing—between scripts from different origins. This kind of communication is defined by HTML5 and is implemented by all current browsers (including IE8 and later). The technique is known as “cross-document messaging,” but since the API is defined on the Window object instead of the document, it might be better known as “inter-window message passing” or “cross-origin messaging.”

The postMessage() method expects two arguments. The ...

Get JavaScript: The Definitive Guide, 6th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.