2

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"
});
JohnSmith1976
  • 536
  • 2
  • 12
  • 35
  • Possible duplicate of [PostMessage from a sandboxed iFrame to the main window, origin is always null](https://stackoverflow.com/questions/37838875/postmessage-from-a-sandboxed-iframe-to-the-main-window-origin-is-always-null) – mems Nov 20 '18 at 16:43
  • Did you ever resolve this? None of the other solutions on this site have resolved this for me. – u84six Aug 19 '20 at 21:53
  • Were you able to solve this? – Neha Agarwal Jul 22 '22 at 15:16

0 Answers0