未收到使用 postMessage()

Using postMessage() isn't being received

我确定这只是我的语法问题,但我正在尝试将变量发送到 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", "*");
});