Hashken
Hashken

Reputation: 4646

javascript - window.postmessage - event.data is always null

I have an iframe and want to send data from the iframe to the parent window.

Inside the js code of the iframe, I have the following statement

window.parent.postMessage('hello', '*');

The corresponding message handler in the parent window is as follows

$(window).bind('message', function (event) {
    console.log(event.data);
    console.log(event.origin);
    console.log(event.source);
    console.log('received');
});

I am loading the code from localhost and the iframe source is also loaded from localhost. I am running the code in firefox 21.

The problem is that event.data is always null and event.orign and event.source are undefined. How do I solve this problem?

Upvotes: 9

Views: 8533

Answers (2)

voiski
voiski

Reputation: 497

See Frédéric Hamidi answer for this. What's happened was the jQuery encapsulate the original event in the proper jQuery.event object type. So, to get the original event you simply need to:

$(window).on("message", function(e) {
  console.log("Orignal:", e.originalEvent);
});

Upvotes: 11

harsh
harsh

Reputation: 1551

window.parent.postMessage('hello', '*');   
window.addEventListener("message", receiveMessage, false);
       function receiveMessage (event) {
            console.log(event.data);
            console.log(event.origin);
            console.log(event.source);
            console.log('received');
        }

This will work as intended; Perhaps there is a problem in event binding("message") with jQuery Will update when get something on that.

Upvotes: 9

Related Questions