我相信这只是我的语法问题,但我正在尝试向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的说明来尝试理解这一切。
receiveMessage
使用了从未被设置的变量origin
,因此它返回。 - Barmarevent
参数的console.log(event)
。这是什么意思? - Barmarorigin
应该是event.origin
,但你为什么要费心处理它呢?它永远不可能是*
,它总是一个 URL。 - Barmarconsole.log(event)
只是为了看看是否有任何显示。在一个 SE 问题上看到别人这样做,我想我也试试。 - Danielmessage
事件监听器并加载页面之前,您已经发送了消息。我使用了setTimeout
函数将发送代码延迟了1秒,这样就解决了问题。 - Barmar