window.top.postMessage发送“ null”作为其event.origin

时间:2018-08-26 19:18:55

标签: javascript iframe

我正在尝试将消息从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"
});

0 个答案:

没有答案