javascript - 未收到使用 postMessage()

标签 javascript postmessage

我确定这只是我的语法问题,但我正在尝试将变量发送到 iframe(供 colorbox 使用)。目前我接受两端的任何域(只是为了让它工作)。这是发送页面的js:

$(document).ready(function() {
 if(window.location.hash) {
  var urlimage = window.location.hash.substring(1);
  targetiframe = document.getElementById('wbgallery').contentWindow;
  targetiframe.postMessage(urlimage, "*");
  console.log(urlimage);
 }
});

这是接收页面:

$(document).ready(function() {    
 window.addEventListener('message',receiveMessage);
 console.log(event);
 function receiveMessage(event) {
   if (origin !== "*")
   return;
   inbound = event.data;
   console.log(inbound);
 }
});

我看到了 urlimage 的控制台日志,并且可以看到一个事件,但没有看到任何入站事件。我正在使用 Mozilla's explanation尝试全力以赴。

最佳答案

您在 iframe 中的页面加载之前发送消息,因此 message 监听器尚未建立。

您可以让 iframe 在准备就绪时向父级发送消息,然后再发送消息。

父代码:

$(document).ready(function() {
  if (window.location.hash) {
    var urlimage = window.location.hash.substring(1);
    var targetiframe = document.getElementById('wbgallery').contentWindow;
    $(window).on("message", function(e) {
      targetiframe.postMessage(urlimage, "*");
      console.log(urlimage);
    });
  }
});

iframe代码:

$(document).ready(function() {
  $(window).on('message', function(event) {
    inbound = event.data;
    console.log(inbound);
  });
  window.parent.postMessage("ready", "*");
});

关于javascript - 未收到使用 postMessage(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40461120/

相关文章:

javascript - Backbone.history.start 从一个特定的片段开始

c# - 为什么PostMessage发送小写按键时会发送多个按键?

javascript - 我如何从 react 中获取消息后数据?

target - 无法在 'postMessage' : target/origin mismatch http vs https 上执行 'DOMWindow'

javascript - 数组推送正在覆盖之前推送的数据

javascript - 在 NodeJS 中发出外部 HTTP 请求的单元测试 Controller 功能

javascript - 仅单击一个按钮即可隐藏/显示元素

数组

delphi - 为什么我的 TFrame "seeing"不是已发布的消息?