gpt4 book ai didi

javascript - 未收到使用 postMessage()

转载 作者:行者123 更新时间:2023-11-29 17:54:35 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com