window.onmessage = ...
window.postMessage('1', '*');
window.postMessage('2', '*');
Does postMessage
(http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#queue-a-task) guarantee the order of events?
postMessage() The window. postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.
Security-Reviewing Uses of postMessage()postMessage is generally considered very secure as long as the programmer is careful to check the origin and source of an arriving message. Acting on a message without verifying its source opens a vector for cross-site scripting attacks.
SendMessage: Sends a message and waits until the procedure which is responsible for the message finishes and returns. PostMessage: Sends a message to the message queue and returns immediately.
The postMessage() function is asynchronous, meaning it will return immediately. So you can not do synchronous communication with it. In your example, the posted message will vanish in the void, because there is no listener for the message event at the time the postMessage() function is executed.
I don't know, although the wording of the spec seems to suggest it doesn't make such guarantees (which is surprising). It's clear that once the MessageEvent
is added to the task queue
on the receiving end, then it's order is maintained, although the MessageEvent
creation and dispatch are asynchronous to the original postMessage
call, so theoretically it appears that you could have the following situation:
main thread:
window.postMessage('1', '*'); --> thread spawned to create MessageEvent
window.postMessage('2', '*'); --> new thread spawned for another MessageEvent
If the thread management system allowed the second postMessage
to execute before the first thread managed to dispatch the MessageEvent
, and for whatever unlucky reason allowed that newer thread to execute (a diluted priority inversion), again before the first managed to dispatch, then you would indeed receive those messages in the reverse order.
Although there might be some other place in the spec that provides more context for these asynchronous executions and rules out this case - I couldn't find it.
window.postMessage()
only triggers a message event on being invoked, and as with classic event publish-subscribe mechanism, there is not real guarantee of the order in their order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With