Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between custom event and postMessage

In order to send a message to another document (let's say an iframe), you can use both postMessage and createEvent functions. Assume this:

var event = document.createEvent('CustomEvent');
event.initCustomEvent("message", true, true, 'Hello world');
iframe.dispatchEvent(event);

My question is, if both approaches work, what is the difference between using postMessage and customEvent?

like image 272
Afshin Mehrabani Avatar asked May 12 '15 06:05

Afshin Mehrabani


People also ask

What is a postMessage?

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.

What is Targetorigin postMessage?

postMessage method allows different windows or iframes to communicate directly, even if they were loaded from different origins, circumventing the usual same-origin policy. The sender of the message can restrict the origin of the receiver by specifying a target origin.

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.

Is postMessage safe?

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.


1 Answers

It's the difference between leaving your neighbour a message asking them to turn down their TV, and trying to break into their apartment to turn down the TV yourself.

You can't dispatch an event into a frame that you are not allowed to access by Same Origin Policy or Access-Control-Allow-Origin, since some of the messages might mess with how that page works. But messages are intended for communication between different pages - if they don't want to listen to the message, they don't have to.

Another difference is that messages must be serialisable, events do not have to be.

like image 82
Amadan Avatar answered Sep 30 '22 17:09

Amadan