<span class="latin" style="width:19px;height:19px;">H</span><span class="latin" style="width:19px;height:19px;">T</span><span class="latin" style="width:19px;height:19px;">M</span><span class="latin" style="width:19px;height:19px;">L</span><span class="latin" style="display:block;width:19px;height:19px;"> </span><span class="latin" style="width:19px;height:19px;">S</span><span class="latin" style="width:19px;height:19px;">t</span><span class="latin" style="width:19px;height:19px;">a</span><span class="latin" style="width:19px;height:19px;">n</span><span class="latin" style="width:19px;height:19px;">d</span><span class="latin" style="width:19px;height:19px;">a</span><span class="latin" style="width:19px;height:19px;">r</span><span class="latin" style="width:19px;height:19px;">d</span>  
(一)9.3 Cross-document messaging
(一)9.3.1 Introduction
(二)9.3.2 Security
(一)9.3.2.1 Authors
(二)9.3.2.2 User agents
(三)9.3.3 Posting messages
(二)9.4 Channel messaging
(一)9.4.1 Introduction
(一)9.4.1.1 Examples
(二)9.4.1.2 Ports as the basis of an object-capability model on the web
(三)9.4.1.3 Ports as the basis of abstracting out service implementations
(二)9.4.2 Message channels
(三)9.4.3 The  MessageEventTarget mixin
(四)9.4.4 Message ports
(五)9.4.5 Ports and garbage collection
(三)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 Android37+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.

(This is a tracking vector.) 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:
 
varo= 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" DOMExceptioniftransfer 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:

Let targetRealmbetargetWindow's realm.
Let incumbentSettings be the incumbent settings object.
Let targetOriginbeoptions["targetOrigin"].
IftargetOrigin is a single U+002F SOLIDUS character (/), then set  targetOrigintoincumbentSettings's origin.


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

Let parsedURL be the result of running the URL parserontargetOrigin.
IfparsedURL is failure, then throw a "SyntaxError"  DOMException.
Set targetOrigintoparsedURL's origin.

Let transferbeoptions["transfer"].
Let serializeWithTransferResultbeStructuredSerializeWithTransfer(message, transfer). Rethrow  any exceptions.

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

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.
Let origin be the serializationofincumbentSettings's origin.
Let source be the WindowProxy object corresponding to  incumbentSettings's global  object (aWindow object).

Let deserializeRecordbeStructuredDeserializeWithTransfer(serializeWithTransferResult,  targetRealm).

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

Let messageClonebedeserializeRecord.[[Deserialized]].
Let newPorts be a new frozen array consisting of all  MessagePort objects in deserializeRecord.[[TransferredValues]], if any,  maintaining their relative order.
Fire an event named messageattargetWindow, 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