I've set up an event listener like this...
window.addEventListener('message', parseMessage, false);
var parseMessage = function(rawMessage) {
console.log(rawMessage.cmd);
};
And then I'm triggering the event like this:
var event = new Event('message', {'cmd':"blerg!"});
window.dispatchEvent(event);
The problem is the console.log in parse message is logging out undefined when I am expecting to to log out "blerg!"
What I am I doing wrong here with the events, how to I pass the 'cmd' message through to the event?
Use CustomEvent
instead of Event
for creating custom events.
Specify your data in a 'details' object (see code).
I changed the event name because message
is also used for the postMessage API. It didn't cause problems when running in Chrome, but I wouldn't use it.
var parseMessage = function(rawMessage) {
console.log(rawMessage);
console.log(rawMessage.detail.cmd);
};
// changed event name
window.addEventListener('myMessage', parseMessage, false);
// data should be in a 'details' object
var evt = new CustomEvent('myMessage', {
detail: {
'cmd' : "blerg!"
}
});
window.dispatchEvent(evt);
Here is an adjustment for IE >= 9 compatiblity (using document.createEvent()
and CustomEvent::initCustomEvent()
):
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent('myMessage', false, false, {
'cmd': "blerg!"
});
For IE9/10 polyfill you can use this code provided by Mozilla:
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
(function () {
if (
typeof window.CustomEvent === "function" ||
// In Safari, typeof CustomEvent == 'object' but it otherwise works fine
this.CustomEvent.toString().indexOf('CustomEventConstructor')>-1
) { return; }
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
Also described here but with wrong URL: https://stackoverflow.com/a/22946340/1736012
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