首页 > 解决方案 > window.top.postMessage 发送“null”作为它的 event.origin

问题描述

我正在尝试将消息从 iframe 发布到父窗口。我当然想origin在处理之前检查消息。但似乎是"null"。我究竟做错了什么?

// 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"
  });
};

iframe 像这样发送它的消息:

// iframe:
<script>
  window.top.postMessage('Hello parent', '*');
</script>

奖励信息:当我向 iframe 发送消息时,我得到了预期的来源:

// Parent:
$(document).ready(function() {
  window.top.postMessage('Hello iframe', '*');
};

// iframe:
window.addEventListener('message', function(event) {
  console.log(event.origin); // "http://localhost:3000"
});

标签: javascriptiframe

解决方案


推荐阅读