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
?
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.
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.
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.
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.
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.
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