共用方式為


postMessage method

Sends a cross-document message.

 

Syntax

var retval = window.postMessage(msg, targetOrigin);

Parameters

  • msg [in]
    Type: BSTR

    A BSTR that contains the message data.

  • targetOrigin [in]
    Type: VARIANT

    A VARIANT of type VT_BSTR that specifies a target URI.

Return value

Type: HRESULT

If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

Remarks

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 IHTMLWindow6::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 HTMLWindowEvents3::onmessage event to the target document on which the IHTMLEventObj5::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 IHTMLWindow6::postMessage method call does not return until the event listeners of the target document have finished executing.

Examples

If Document A contains a reference to the IHTMLFrameBase2::contentWindow property of Document B, script in Document A can send a message to Document B by calling the IHTMLWindow6::postMessage method as follows:

var o = document.getElementsByTagName('iframe')[0];
o.contentWindow.postMessage('Hello World');

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

window.addEventListener('message', function(e) {
    if (e.domain == 'example.com') {
        if (e.data == 'Hello World') {
            e.source.postMessage('Hello');
        } else {
            alert(e.data);
        }
    }
});

See also

window

HTMLWindowEvents3::onmessage