65

When I use jQuery event listener to handle message event, like below:

$(window).on('message', function(e) {
    var data = e.data; // data = undefined
});

data is undefined! I'm sure that I have passed data to current window. Because if I use "addEventListener", everything goes well!

So, what's the problem?

Ionică Bizău
  • 93,552
  • 74
  • 254
  • 426
stefan
  • 2,217
  • 3
  • 13
  • 11

2 Answers2

113

jQuery might be preprocessing the event's data property, and this operation may not properly support the message event (yet).

Try using the originalEvent property to fetch your data:

$(window).on("message", function(e) {
    var data = e.originalEvent.data;  // Should work.
});
Frédéric Hamidi
  • 240,249
  • 39
  • 455
  • 462
  • 3
    A +1 for you, this just helped me stop pulling my hair out. – ceejayoz Aug 09 '13 at 21:35
  • 1
    What is the best way to also handle "onmessage" in IE? – grim Mar 05 '14 at 11:32
  • 1
    @grim, IE has problems in its support for `postMessage()`. See https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage#Browser_compatibility and [Is cross-origin postMessage broken in IE10?](http://stackoverflow.com/q/16226924/464709). – Frédéric Hamidi Mar 05 '14 at 11:39
  • +1 - a solution I was looking for. yet I could not unbind the event using `$(window).off("message")`. on the other hand, `$(window).bind / $(window).unbind` successfully attached / detached for me a handler to the `message` event. – Vitali Climenco Dec 17 '15 at 13:25
13

Some browsers use the "onmessage" event. I suggest a little improvement to the previous answer for increased compatibility:

$(window).on("message onmessage", function(e) {
    var data = e.originalEvent.data;
});
Tibor
  • 198
  • 1
  • 5