20

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?

1

2 Answers 2

49
  1. Use CustomEvent instead of Event for creating custom events.

  2. Specify your data in a 'details' object (see code).

  3. 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!"
});
5
  • That's brilliant thanks, just wondering, does it have to be inside an json called 'detail' or is that something you've added?
    – CafeHey
    Oct 13, 2013 at 17:04
  • 1
    @Smickie Your custom data has to live in the 'detail' key. It doesn't work otherwise. (Btw, it isn't called a 'json'. 'detail' is a so-called "key").
    – ComFreek
    Oct 13, 2013 at 17:10
  • Nice answer. Btw, Object Literal is the term your looking for typeof ({detail:{cmd:'blerg!'}}).detail ;-)
    – LessQuesar
    Aug 4, 2016 at 13:18
  • Might be worth adding that you can use Modernizr to detect if CustomEvent is supported then you can choose which approach to use to create your event. Aug 10, 2016 at 7:06
  • 1
    See MDN Polyfill in the answer of @olefrank
    – Ilker Cat
    Jun 7, 2018 at 9:44
27

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

4
  • 1
    This also fixes it in IE11 Jun 1, 2016 at 10:48
  • 1
    Its not only fixing IE9/10 but IE11 as well ;)
    – Ilker Cat
    Jun 7, 2018 at 9:42
  • Thanks for this fix Mar 6, 2020 at 18:54
  • I've also had to add the line window.Event = CustomEvent; for IE11, to allow for supporting code like new Event("myEvent")
    – Jay
    Jul 1, 2020 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.