Search code examples
javascripthtmlpostmessagecustom-events

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?


Solution

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