Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 310
Hashken Avatar asked Jun 19 '13 11:06

Hashken


2 Answers

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);
});
like image 90
voiski Avatar answered Oct 20 '22 02:10

voiski


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.

like image 26
harsh Avatar answered Oct 20 '22 02:10

harsh