GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||
GeezerVison is showing html.spec.whatwg.org — HTML Standard 9.3 Cross-document messagingSupport 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.
9.3.1 IntroductionThis section is non-normative. For example, if document A contains an
To register an event handler for incoming events, the script would use
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 Security9.3.2.1 AuthorsUse of this API requires extra care to protect users from hostile entities abusing a site for their own purposes. Authors should check the Furthermore, even after checking the 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 agentsThe integrity of this API is based on the inability for scripts of one origin to
post arbitrary events (using 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
When posting a message to a The window post message steps, given a targetWindow, message, and options, are as follows:
The The 9.4 Channel messagingSupport 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+ Channel_Messaging_API/Using_channel_messaging 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+ 9.4.1 IntroductionThis section is non-normative. To enable independent pieces of code (e.g. running in different browsing contexts) to communicate directly, authors can use channel messaging. Communication channels in this mechanism are implemented as two-ways pipes, with a port at each end. Messages sent in one port are delivered at the other port, and vice-versa. Messages are delivered as DOM events, without interrupting or blocking running tasks. To create a connection (two "entangled" ports), the
One of the ports is kept as the local port, and the other port is sent to the remote code, e.g.
using
To send messages, the
To receive messages, one listens to
Data sent on a port can be structured data; for example here an array of strings is passed on a
9.4.1.1 ExamplesThis section is non-normative. In this example, two JavaScript libraries are connected to each other using
Here's what the "addContactsProvider()" function's implementation could look like:
Alternatively, it could be implemented as follows:
The key difference is that when using The 9.4.1.2 Ports as the basis of an object-capability model on the webThis section is non-normative. Ports can be viewed as a way to expose limited capabilities (in the object-capability model sense) to other actors in the system. This can either be a weak capability system, where the ports are merely used as a convenient model within a particular origin, or as a strong capability model, where they are provided by one origin provider as the only mechanism by which another origin consumer can effect change in or obtain information from provider. For example, consider a situation in which a social web site embeds in one
The contacts provider can use these methods, most particularly the third one, to provide an API
that can be accessed by other origins to manipulate the user's address book. For example, it could
respond to a message " To avoid any site on the web being able to manipulate the user's contacts, the contacts provider might only allow certain trusted sites, such as the social site, to do this. Now suppose the game wanted to add a contact to the user's address book, and that the social site was willing to allow it to do so on its behalf, essentially "sharing" the trust that the contacts provider had with the social site. There are several ways it could do this; most simply, it could just proxy messages between the game site and the contacts site. However, this solution has a number of difficulties: it requires the social site to either completely trust the game site not to abuse the privilege, or it requires that the social site verify each request to make sure it's not a request that it doesn't want to allow (such as adding multiple contacts, reading the contacts, or deleting them); it also requires some additional complexity if there's ever the possibility of multiple games simultaneously trying to interact with the contacts provider. Using message channels and 9.4.1.3 Ports as the basis of abstracting out service implementationsThis section is non-normative. Continuing the example from the previous section, consider the contacts provider in particular.
While an initial implementation might have simply used If the initial design used 9.4.2 Message channelsSupport 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+
A The
9.4.3 The
|
| Event handler | Event handler event type |
|---|---|
onmessage Support in all current engines. Firefox41+Safari5+Chrome2+ Opera10.6+Edge79+ Edge (Legacy)12+Internet Explorer10+ Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11.5+ DedicatedWorkerGlobalScope/message_event Support in all current engines. Firefox3.5+Safari4+Chrome4+ Opera10.6+Edge79+ Edge (Legacy)12+Internet Explorer10+ Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android11.5+ | message
|
onmessageerror MessagePort/messageerror_event Support in all current engines. Firefox57+Safari16.4+Chrome60+ Opera?Edge79+ Edge (Legacy)18Internet ExplorerNo Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+ DedicatedWorkerGlobalScope/messageerror_event Support in all current engines. Firefox57+Safari16.4+Chrome60+ Opera?Edge79+ Edge (Legacy)18Internet ExplorerNo Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+ | messageerror
|
Support in all current engines.
Each channel has two message ports. Data sent through one port is received by the other port, and vice versa.
[Exposed =(Window ,Worker ,AudioWorklet ), Transferable ]
interface MessagePort : EventTarget {
undefined postMessage (any message , sequence <object > transfer );
undefined postMessage (any message , optional StructuredSerializeOptions options = {});
undefined start ();
undefined close ();
};
MessagePort includes MessageEventTarget ;
dictionary StructuredSerializeOptions {
sequence <object > transfer = [];
};
port.postMessage(message [, transfer])Support in all current engines.
port.postMessage(message [, { transfer }])Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side.
Throws a "DataCloneError" DOMException if
transfer contains duplicate objects or port, or if message
could not be cloned.
port.start()Support in all current engines.
Begins dispatching messages received on the port.
port.close()Support in all current engines.
Disconnects the port, so that it is no longer active.
Each MessagePort object has a message event target (a
MessageEventTarget), to which the message and messageerror events are dispatched. Unless otherwise
specified, it defaults to the MessagePort object itself.
Each MessagePort object can be entangled with another (a symmetric relationship).
Each MessagePort object also has a task source called the port
message queue, initially empty. A port message queue can be enabled or
disabled, and is initially disabled. Once enabled, a port can never be disabled again (though
messages in the queue can get moved to another queue or removed altogether, which has much the
same effect). A MessagePort also has a has been shipped flag, which must
initially be false.
When a port's port message queue is enabled, the event loop must use
it as one of its task sources. When a port's relevant
global object is a Window, all tasks queued on its port message queue must be associated with
the port's relevant global object's associated
Document.
If the document is fully active, but the event listeners were all created in the context of documents that are not fully active, then the messages will not be received unless and until the documents become fully active again.
Each event loop has a task source called the unshipped port
message queue. This is a virtual task source: it must act as if it contained
the tasks of each port message queue of each
MessagePort whose has been shipped flag is false, whose port
message queue is enabled, and whose relevant agent's event loop is that event loop, in the order
in which they were added to their respective task source. When a task would be removed from the unshipped port message
queue, it must instead be removed from its port message queue.
When a MessagePort's has been shipped flag is false, its port
message queue must be ignored for the purposes of the event loop. (The
unshipped port message queue is used instead.)
The has been shipped flag is set to true when a port, its twin, or
the object it was cloned from, is or has been transferred. When a MessagePort's
has been shipped flag is true, its port message queue acts as a
first-class task source, unaffected to any unshipped port message
queue.
When the user agent is to entangle two MessagePort objects, it must run
the following steps:
If one of the ports is already entangled, then disentangle it and the port that it was entangled with.
If those two previously entangled ports were the two ports of a
MessageChannel object, then that MessageChannel object no longer
represents an actual channel: the two ports in that object are no longer entangled.
Associate the two ports to be entangled, so that they form the two parts of a new channel.
(There is no MessageChannel object that represents this channel.)
Two ports A and B that have gone through this step are now said to be entangled; one is entangled to the other, and vice versa.
While this specification describes this process as instantaneous, implementations are more likely to implement it via message passing. As with all algorithms, the key is "merely" that the end result be indistinguishable, in a black-box sense, from the specification.
The disentangle steps, given a MessagePort initiatorPort
which initiates disentangling, are as follows:
Let otherPort be the MessagePort which initiatorPort
was entangled with.
Assert: otherPort exists.
Disentangle initiatorPort and otherPort, so that they are no longer entangled or associated with each other.
MessagePort objects are transferable
objects. Their transfer steps, given value and
dataHolder, are:
Set value's has been shipped flag to true.
Set dataHolder.[[PortMessageQueue]] to value's port message queue.
If value is entangled with another port remotePort:
Set remotePort's has been shipped flag to true.
Set dataHolder.[[RemotePort]] to remotePort.
Otherwise, set dataHolder.[[RemotePort]] to null.
Their transfer-receiving steps, given dataHolder and value, are:
Set value's has been shipped flag to true.
Move all the tasks that are to fire message events in dataHolder.[[PortMessageQueue]] to the
port message queue of value, if any, leaving value's
port message queue in its initial disabled state, and, if value's
relevant global object is a Window, associating the moved tasks with value's relevant global object's
associated Document.
If dataHolder.[[RemotePort]] is not null, then entangle dataHolder.[[RemotePort]] and value. (This will disentangle dataHolder.[[RemotePort]] from the original port that was transferred.)
The message port post message steps, given sourcePort, targetPort, message, and options are as follows:
Let transfer be options["transfer"].
If transfer contains
sourcePort, then throw a "DataCloneError"
DOMException.
Let doomed be false.
If targetPort is not null and transfer contains targetPort, then set doomed to true and optionally report to a developer console that the target port was posted to itself, causing the communication channel to be lost.
Let serializeWithTransferResult be StructuredSerializeWithTransfer(message, transfer). Rethrow any exceptions.
If targetPort is null, or if doomed is true, then return.
Add a task that runs the following steps to the port message queue of targetPort:
Let finalTargetPort be the MessagePort in whose port message
queue the task now finds itself.
This can be different from targetPort, if targetPort itself was transferred and thus all its tasks moved along with it.
Let messageEventTarget be finalTargetPort's message event target.
Let targetRealm be finalTargetPort's relevant realm.
Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).
If this throws an exception, catch it, fire an
event named messageerror at
messageEventTarget, using MessageEvent, and then return.
Let messageClone be deserializeRecord.[[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 message at messageEventTarget, using
MessageEvent, with the data attribute
initialized to messageClone and the ports attribute initialized to
newPorts.
The postMessage(message,
options) method steps are:
Let targetPort be the port with which this is entangled, if any; otherwise let it be null.
Run the message port post message steps providing this, targetPort, message and options.
The postMessage(message,
transfer) method steps are:
Let targetPort be the port with which this is entangled, if any; otherwise let it be null.
Let options be «[ "transfer" → transfer
]».
Run the message port post message steps providing this, targetPort, message and options.
The start()
method steps are to enable this's port message queue, if it is not
already enabled.
The close()
method steps are:
Set this's [[Detached]] internal slot value to true.
If this is entangled, disentangle it.
The first time a MessagePort object's onmessage IDL attribute is set, the port's
port message queue must be enabled, as if the start() method had been called.
This section is non-normative.
Broadcasting to many ports is in principle relatively simple: keep an array of
MessagePort objects to send messages to, and iterate through the array to send a
message. However, this has one rather unfortunate effect: it prevents the ports from being garbage
collected, even if the other side has gone away. To avoid this problem, implement a simple
protocol whereby the other side acknowledges it still exists. If it doesn't do so after a certain
amount of time, assume it's gone, close the MessagePort object, and let it be garbage
collected.
When a MessagePort object o is entangled, user agents must either act
as if o's entangled MessagePort object has a strong reference to
o, or as if o's relevant global object has a strong reference
to o.
Thus, a message port can be received, given an event listener, and then forgotten, and so long as that event listener could receive a message, the channel will be maintained.
Of course, if this was to occur on both sides of the channel, then both ports could be garbage collected, since they would not be reachable from live code, despite having a strong reference to each other.
Furthermore, a MessagePort object must not be garbage collected while there
exists an event referenced by a task in a task
queue that is to be dispatched on that MessagePort object, or while the
MessagePort object's port message queue is enabled and not empty.
Authors are strongly encouraged to explicitly close MessagePort
objects to disentangle them, so that their resources can be recollected. Creating many
MessagePort objects and discarding them without closing them can lead to high
transient memory usage since garbage collection is not necessarily performed promptly, especially
for MessagePorts where garbage collection can involve cross-process coordination.
Support in all current engines.
Support in all current engines.
Pages on a single origin opened by the same user in the same user agent but in different unrelated browsing contexts sometimes need to send notifications to each other, for example "hey, the user logged in over here, check your credentials again".
For elaborate cases, e.g. to manage locking of shared state, to manage synchronization of
resources between a server and multiple local clients, to share a WebSocket
connection with a remote host, and so forth, shared workers are
the most appropriate solution.
For simple cases, though, where a shared worker would be an unreasonable overhead, authors can use the simple channel-based broadcast mechanism described in this section.
[Exposed =(Window ,Worker )]
interface BroadcastChannel : EventTarget {
constructor (DOMString name );
readonly attribute DOMString name ;
undefined postMessage (any message );
undefined close ();
attribute EventHandler onmessage ;
attribute EventHandler onmessageerror ;
};
broadcastChannel = new BroadcastChannel(name)BroadcastChannel/BroadcastChannel
Support in all current engines.
Returns a new BroadcastChannel object via which messages for the given channel
name can be sent and received.
broadcastChannel.nameSupport in all current engines.
Returns the channel name (as passed to the constructor).
broadcastChannel.postMessage(message)Support in all current engines.
Sends the given message to other BroadcastChannel objects set up for this
channel. Messages can be structured objects, e.g. nested objects and arrays.
broadcastChannel.close()Support in all current engines.
Closes the BroadcastChannel object, opening it up to garbage
collection.
A BroadcastChannel object has a channel name and a closed flag.
The new BroadcastChannel(name)
constructor steps are:
Set this's channel name to name.
Set this's closed flag to false.
The name getter steps are to return
this's channel name.
A BroadcastChannel object is said to be eligible for messaging when
its relevant global object is either:
a Window object whose associated
Document is fully active, or
a WorkerGlobalScope object whose closing flag is false and is not suspendable.
The postMessage(message) method
steps are:
If this is not eligible for messaging, then return.
If this's closed flag
is true, then throw an "InvalidStateError"
DOMException.
Let serialized be StructuredSerialize(message). Rethrow any exceptions.
Let sourceOrigin be this's relevant settings object's origin.
Let sourceStorageKey be the result of running obtain a storage key for non-storage purposes with this's relevant settings object.
Let destinations be a list of BroadcastChannel objects that
match the following criteria:
They are eligible for messaging.
The result of running obtain a storage key for non-storage purposes with their relevant settings object equals sourceStorageKey.
Their channel name is this's channel name.
Remove source from destinations.
Sort destinations such that all BroadcastChannel objects whose
relevant agents are the same are sorted in creation order,
oldest first. (This does not define a complete ordering. Within this constraint, user agents may
sort the list in any implementation-defined manner.)
For each destination in destinations, queue a global task on the DOM manipulation task source given destination's relevant global object to perform the following steps:
If destination's closed flag is true, then abort these steps.
Let targetRealm be destination's relevant realm.
Let data be StructuredDeserialize(serialized, targetRealm).
If this throws an exception, catch it, fire an
event named messageerror at
destination, using MessageEvent, with its origin initialized to sourceOrigin, and
then abort these steps.
Fire an event named message at destination, using
MessageEvent, with the data attribute
initialized to data and its origin initialized to
sourceOrigin.
While a BroadcastChannel object whose closed flag is false has an event listener
registered for message or messageerror events, there must be a strong reference from the
BroadcastChannel object's relevant global object to the
BroadcastChannel object itself.
The close() method steps are to set
this's closed flag to true.
Authors are strongly encouraged to explicitly close BroadcastChannel
objects when they are no longer needed, so that they can be garbage collected. Creating many
BroadcastChannel objects and discarding them while leaving them with an event
listener and without closing them can lead to an apparent memory leak, since the objects will
continue to live for as long as they have an event listener (or until their page or worker is
closed).
The following are the event handlers (and their corresponding event handler event types) that must be supported,
as event handler IDL attributes, by all objects implementing the
BroadcastChannel interface:
| Event handler | Event handler event type |
|---|---|
onmessage BroadcastChannel/message_event Support in all current engines. Firefox38+Safari15.4+Chrome54+ Opera?Edge79+ Edge (Legacy)?Internet ExplorerNo Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android? | message
|
onmessageerror BroadcastChannel/messageerror_event Support in all current engines. Firefox57+Safari15.4+Chrome60+ Opera?Edge79+ Edge (Legacy)?Internet ExplorerNo Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+ | messageerror
|
Suppose a page wants to know when the user logs out, even when the user does so from another tab at the same site:
var authChannel = new BroadcastChannel( 'auth' );
authChannel. onmessage = function ( event) {
if ( event. data == 'logout' )
showLogout();
}
function logoutRequested() {
// called when the user asks us to log them out
doLogout();
showLogout();
authChannel. postMessage( 'logout' );
}
function doLogout() {
// actually log the user out (e.g. clearing cookies)
// ...
}
function showLogout() {
// update the UI to indicate we're logged out
// ...
}