[go: nahoru, domu]

    1. 9.3 Cross-document messaging
      1. 9.3.1 Introduction
      2. 9.3.2 Security
        1. 9.3.2.1 Authors
        2. 9.3.2.2 User agents
      3. 9.3.3 Posting messages
    2. 9.4 Channel messaging
      1. 9.4.1 Introduction
        1. 9.4.1.1 Examples
        2. 9.4.1.2 Ports as the basis of an object-capability model on the web
        3. 9.4.1.3 Ports as the basis of abstracting out service implementations
      2. 9.4.2 Message channels
      3. 9.4.3 Message ports
      4. 9.4.4 Ports and garbage collection
    3. 9.5 Broadcasting to other browsing contexts

9.3 Cross-document messaging

Window/postMessage

Support in all current engines.

Firefox3+Safari4+Chrome2+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android≤37+Samsung Internet?Opera Android10.1+

Web browsers, for security and privacy reasons, prevent documents in different domains from affecting each other; that is, cross-site scripting is disallowed.

While this is an important security feature, it prevents pages from different domains from communicating even when those pages are not hostile. This section introduces a messaging system that allows documents to communicate with each other regardless of their source domain, in a way designed to not enable cross-site scripting attacks.

The postMessage() API can be used as a tracking vector.

9.3.1 Introduction

This section is non-normative.

For example, if document A contains an iframe element that contains document B, and script in document A calls postMessage() on the Window object of document B, then a message event will be fired on that object, marked as originating from the Window of document A. The script in document A might look like:

var o = document.getElementsByTagName('iframe')[0];
o.contentWindow.postMessage('Hello world', 'https://b.example.org/');

To register an event handler for incoming events, the script would use addEventListener() (or similar mechanisms). For example, the script in document B might look like:

window.addEventListener('message', receiver, false);
function receiver(e) {
  if (e.origin == 'https://example.com') {
    if (e.data == 'Hello world') {
      e.source.postMessage('Hello', e.origin);
    } else {
      alert(e.data);
    }
  }
}

This script first checks the domain is the expected domain, and then looks at the message, which it either displays to the user, or responds to by sending a message back to the document which sent the message in the first place.

9.3.2 Security

9.3.2.1 Authors

Use of this API requires extra care to protect users from hostile entities abusing a site for their own purposes.

Authors should check the origin attribute to ensure that messages are only accepted from domains that they expect to receive messages from. Otherwise, bugs in the author's message handling code could be exploited by hostile sites.

Furthermore, even after checking the origin attribute, authors should also check that the data in question is of the expected format. Otherwise, if the source of the event has been attacked using a cross-site scripting flaw, further unchecked processing of information sent using the postMessage() method could result in the attack being propagated into the receiver.

Authors should not use the wildcard keyword (*) in the targetOrigin argument in messages that contain any confidential information, as otherwise there is no way to guarantee that the message is only delivered to the recipient to which it was intended.


Authors who accept messages from any origin are encouraged to consider the risks of a denial-of-service attack. An attacker could send a high volume of messages; if the receiving page performs expensive computation or causes network traffic to be sent for each such message, the attacker's message could be multiplied into a denial-of-service attack. Authors are encouraged to employ rate limiting (only accepting a certain number of messages per minute) to make such attacks impractical.

9.3.2.2 User agents

The integrity of this API is based on the inability for scripts of one origin to post arbitrary events (using dispatchEvent() or otherwise) to objects in other origins (those that are not the same).

Implementers are urged to take extra care in the implementation of this feature. It allows authors to transmit information from one domain to another domain, which is normally disallowed for security reasons. It also requires that UAs be careful to allow access to certain properties but not others.


User agents are also encouraged to consider rate-limiting message traffic between different origins, to protect naïve sites from denial-of-service attacks.

9.3.3 Posting messages

window.postMessage(message [, options ])

Window/postMessage

Support in all current engines.

Firefox3+Safari4+Chrome2+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

Posts a message to the given window. Messages can be structured objects, e.g. nested objects and arrays, can contain JavaScript values (strings, numbers, Date objects, etc.), and can contain certain data objects such as File Blob, FileList, and ArrayBuffer objects.

Objects listed in the transfer member of options are transferred, not just cloned, meaning that they are no longer usable on the sending side.

A target origin can be specified using the targetOrigin member of options. If not provided, it defaults to "/". This default restricts the message to same-origin targets only.

If the origin of the target window doesn't match the given target origin, the message is discarded, to avoid information leakage. To send the message to the target regardless of origin, set the target origin to "*".

Throws a "DataCloneError" DOMException if transfer array contains duplicate objects or if message could not be cloned.

window.postMessage(message, targetOrigin [, transfer ])

This is an alternate version of postMessage() where the target origin is specified as a parameter. Calling window.postMessage(message, target, transfer) is equivalent to window.postMessage(message, {targetOrigin, transfer}).

When posting a message to a Window of a browsing context that has just been navigated to a new Document is likely to result in the message not receiving its intended recipient: the scripts in the target browsing context have to have had time to set up listeners for the messages. Thus, for instance, in situations where a message is to be sent to the Window of newly created child iframe, authors are advised to have the child Document post a message to their parent announcing their readiness to receive messages, and for the parent to wait for this message before beginning posting messages.

The window post message steps, given a targetWindow, message, and options, are as follows:

  1. Let targetRealm be targetWindow's realm.

  2. Let incumbentSettings be the incumbent settings object.

  3. Let targetOrigin be options["targetOrigin"].

  4. If targetOrigin is a single U+002F SOLIDUS character (/), then set targetOrigin to incumbentSettings's origin.

  5. Otherwise, if targetOrigin is not a single U+002A ASTERISK character (*), then:

    1. Let parsedURL be the result of running the URL parser on targetOrigin.

    2. If parsedURL is failure, then throw a "SyntaxError" DOMException.

    3. Set targetOrigin to parsedURL's origin.

  6. Let transfer be options["transfer"].

  7. Let serializeWithTransferResult be StructuredSerializeWithTransfer(message, transfer). Rethrow any exceptions.

  8. Queue a global task on the posted message task source given targetWindow to run the following steps:

    1. If the targetOrigin argument is not a single literal U+002A ASTERISK character (*) and targetWindow's associated Document's origin is not same origin with targetOrigin, then return.

    2. Let origin be the serialization of incumbentSettings's origin.

    3. Let source be the WindowProxy object corresponding to incumbentSettings's global object (a Window object).

    4. Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).

      If this throws an exception, catch it, fire an event named messageerror at targetWindow, using MessageEvent, with the origin attribute initialized to origin and the source attribute initialized to source, and then return.

    5. Let messageClone be deserializeRecord.[[Deserialized]].

    6. Let newPorts be a new frozen array consisting of all MessagePort objects in deserializeRecord.[[TransferredValues]], if any, maintaining their relative order.

    7. Fire an event named message at targetWindow, using MessageEvent, with the origin attribute initialized to origin, the source attribute initialized to source, the data attribute initialized to messageClone, and the ports attribute initialized to newPorts.

The Window interface's postMessage(message, options) method steps are to run the window post message steps given this, message, and options.

The Window interface's postMessage(message, targetOrigin, transfer) method steps are to run the window post message steps given this, message, and «[ "targetOrigin" → targetOrigin, "transfer" → transfer ]».

9.4 Channel messaging

Channel_Messaging_API

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

elements, the main document and a single