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?
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);
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With