Search code examples
javascriptfirefoxiframepostmessage

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?


Solution

  • 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.