This page is Ready to Use

Notice: The WebPlatform project has been discontinued when the Stewards partnership agreement ended in September 2015. This site has been frozen, and the assets we have created will remain.

postMessage

Summary

Sends a cross-document message.

Method of dom/Windowdom/Window

Syntax

 targetFrame.postMessage(/* see parameter list */);

Parameters

msg

Data-type
String

A String that contains the message data.

targetOrigin

Data-type
String

A Variant of type String that specifies a target URI.

Return Value

No return value

Examples

If Document A (on http://127.0.0.1) contains a reference to the contentWindow property of Document B (on http://localhost), script in Document A can send a message to Document B by calling the postMessage method as follows:

var targetframe = document.getElementsByTagName('iframe')[0];
targetframe.contentWindow.postMessage('Hello World','http://localhost');

The script in Document B can respond to the message by registering the onmessage event handler for incoming messages.

window.addEventListener('message',function(e) {
    if (e.origin == 'http://127.0.0.1') {
        if (e.data == 'Hello World') {
            // We can reply with this
            e.source.postMessage('Hello');
        } else {
            console.log(e);
        }
    }
},false);

Notes

**Security Warning: **While “*” is a valid value for targetOrigin, set the parameter to the value you expected to receive; otherwise, the security of your message might be compromised. For more information about this security message, see Section 3.1.2 of the HTML5 Web Messaging Specification (Editor’s Draft) from the World Wide Web Consortium (W3C). The postMessage method allows cooperative text exchange between untrusted modules from different domains embedded within a page. It does so by ensuring a consistent and secure process for text-based data exchange. When a script invokes this method on a window object, the browser sends an onmessage event to the target document on which the data property has been set to the value passed in msg. When a target URI is passed into the method, it must have at least a protocol and a host specified. The message will only be sent if the target window has the same protocol and host as the specified target URI. The postMessage method call does not return until the event listeners of the target document have finished executing.

Standards information

Attributions