Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does window.postMessage guarantee the order of events?

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?

like image 554
4esn0k Avatar asked Sep 24 '11 03:09

4esn0k


People also ask

What is window postMessage () used for?

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.

Is window postMessage secure?

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.

What is the difference between SendMessage and postMessage?

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.

Is postMessage asynchronous?

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.


2 Answers

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.

like image 153
davin Avatar answered Oct 11 '22 04:10

davin


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.

like image 24
Saket Avatar answered Oct 11 '22 03:10

Saket