Dan*_*iel 6 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);
}
});
Run Code Online (Sandbox Code Playgroud)
这是接收页面:
$(document).ready(function() {
window.addEventListener('message',receiveMessage);
console.log(event);
function receiveMessage(event) {
if (origin !== "*")
return;
inbound = event.data;
console.log(inbound);
}
});
Run Code Online (Sandbox Code Playgroud)
我看到了 urlimage 的控制台日志,可以看到一个事件,但没有任何入站事件。我正在使用Mozilla 的解释来尝试解决所有问题。
您在 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);
});
}
});
Run Code Online (Sandbox Code Playgroud)
框架代码:
$(document).ready(function() {
$(window).on('message', function(event) {
inbound = event.data;
console.log(inbound);
});
window.parent.postMessage("ready", "*");
});
Run Code Online (Sandbox Code Playgroud)