I'm trying to post a message from an iframe to the parent window. I of course want to check the origin
of the message before processing it. But it seems to be "null"
. What am I doing wrong?
// Parent:
$(document).ready(function() {
loadIframe();
iframeListen();
});
loadIframe = function() {
var iframe;
iframe = document.createElement('iframe');
iframe.src = "/load_pages.htm";
iframe.sandbox = "allow-scripts";
iframe.id = "page_iframe";
iframe.onload = function() {
return postToIframe();
};
return document.body.appendChild(iframe);
};
iframeListen = function() {
return window.addEventListener('message', function(event) {
return console.log(event.origin); // "null"
});
};
The iframe sends its message like this:
// iframe:
<script>
window.top.postMessage('Hello parent', '*');
</script>
Bonus info: When I send messages to the iframe I get the expected origin:
// Parent:
$(document).ready(function() {
window.top.postMessage('Hello iframe', '*');
};
// iframe:
window.addEventListener('message', function(event) {
console.log(event.origin); // "http://localhost:3000"
});