Difference between custom event and postMessage

To send a message to another document (for example iframe

), you can use the postMessage

and functions createEvent

. Let's assume the following:

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

?

+3


source to share


1 answer


The difference is to leave your neighbor a message asking them to give up the TV and sneak into their apartment and turn off the TV yourself.

You cannot send an event to a frame that you are not allowed to access using the Same Origin Policy or Access-Control-Allow-Origin, as some of the messages may interfere with this page. But messages are meant to communicate between different pages - if they don't want to listen to the message, they don't need to.



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

+5


source







All Articles