Cross-window messaging

Web pages often consist of multiple frames that coexist on a single visual page. A good example are advertisements, which are semantically not part of the content of the actual page and technically separated into an own frame. The consequence of this separation is that such ads have their own context and cannot access the context of the main web page. This is a necessary security measure, since otherwise ads would be able to spy on the user as he interacts with the web application. Sometimes however, it is necessary to split a single web application into multiple frames for technical reasons even if they belong together from a semantic point of view. Such an example would be a SVG graphic nested in its own <em>iframe</em> within a web application. Let's take an application as an example, that has a SVG graphic with selectable areas which the user can click on, that then displays data for the selected area in the main application. The browser forbids direct JavaScript interaction like function calls or changes of variables between the main frame and the frame that contains the SVG graphic, making it impossible to notify the web application about the users action in the graphic.
1 answer

Cross-window messaging with window.postMessage

HTML5 offers a new API for communication between different windows/frames.

First, a reference to the iframe must be obtained. This can be done with regular JavaScript and DOM functions. While the content of the iframe remains hidden even with HTML5, it is possible to send a text message to the iframe with iframe.postMessage(message, targetOrigin); where iframe denotes the reference to the iframe, message the text message and targetOrigin is used to identify the sender of the message.

In order to receive the message, the receiving iframe must add an event listener like window.addEventListener("message", receiveMessage, false); with the parameter receiveMessage being a reference to a function that handles incoming messages. It can look like this:

function receiveMessage(event) {
if(event.origin != /* expected message sender */)
// malicious message
else {
var message = event.data;
// proceed with code
}
}