Javascript 如何确保使用PostMessageAPI时弹出窗口已完全加载?
如您所知,使用html5的API postMessage,我们可以将消息发布到当前页面的iframe或新的弹出窗口,但如果我们这样编码:Javascript 如何确保使用PostMessageAPI时弹出窗口已完全加载?,javascript,html,sendmessage,Javascript,Html,Sendmessage,如您所知,使用html5的API postMessage,我们可以将消息发布到当前页面的iframe或新的弹出窗口,但如果我们这样编码: var popwindow = window.open('http://localhost:8080/index2.html'); popwindow.postMessage({"age":10}, 'http://localhost:8080/index2.html'); 当弹出窗口尚未加载时,我们将不会收到消息,因为我们使用“postMessag
var popwindow = window.open('http://localhost:8080/index2.html');
popwindow.postMessage({"age":10},
'http://localhost:8080/index2.html');
当弹出窗口尚未加载时,我们将不会收到消息,因为我们使用“postMessage”,因此如何确保已加载弹出窗口?我们无法在当前页面中使用popwindow.onload,因此如何才能使用?请帮帮我~谢谢你可以用
window.opener.postMessage(...
在index2.html中,向开证人发出已加载的信号
或者,有一种古老的方式:
在index.html中
function imOpen(win) {
win.postMessage(// whatever ...
}
window.open('index2.html');
在index2.html中
window.addEventListener('load', function() {
window.opener.imOpen(window);
});
这种方式使用的弹出窗口不需要PostMessageAPI
//Inside parent window
var data = {age: 10}; //No quotes around age
window.open('http://localhost:8080/index2.html');
//Inside popup window
var sameData = window.opener.data;
不过,无可否认,您可能不应该通过window.open(…)使用弹出窗口,因为它们一直被阻止
如果使用iframe模式,您可能可以通过执行以下操作获得postMessage
的工作方式
//In iframe
window.addEventListener("message", iframeReceiveMessage);
document.addEventListener("DOMContentLoaded", function() {
//JSON data for message
window.parent.postMessage("iframe is ready", "http://localhost:8080");
});
function iframeReceiveMessage(event) {
var iframeData = JSON.parse(event.message);
//iframeData.age === 10
}
然后通过以下方式收听家长的讲话:
//In parent
window.addEventListener("message", parentReceiveMessage);
function parentReceiveMessage(event)
{
if (event.origin !== "http://localhost:8080" && event.message !== "iframe is ready") { return; }
var iframe = document.getElementById("iframeId").contentWindow,
parentData = {age: 10};
iframe.postMessage(JSON.stringify(parentData), "http://localhost:8080");
}
由于某些浏览器只接受postMessage响应中的字符串,因此您必须将数据转换为JSON
不过,发送对象数据可能有点过头了。如果您已经在同一个域上,是否考虑过使用sessionStorage?
您仍然需要使用JSON.stringify和JSON.parse(sessionStorage仅存储字符串),但它非常简单:
//Store it
var data = {age: 10};
sessionStorage.data = JSON.stringify(data);
//Use it
var newData = JSON.parse(sessionStorage.data);
//Remove it
sessionStorage.removeItem("data");
这种方法的一个缺点是,HTTPS页面的sessionStorage是独立的,因此您无法在这两个协议之间发送sessionStorage数据 我试过这种方法,似乎“window.opener.imOpen(window);”没有按预期工作,我不知道为什么。似乎如果我们要使用“window.opener.imOpen(window);”,这两个URL必须是相同的源代码,您应该更新这个问题,说明您的问题是跨域URL。此示例仅适用于相同的域URL。一旦你进入跨域,你就不能使用window.opener…你会得到一个跨域安全异常。@Caydynyc-这个问题/答案已经有5年历史了:p@JaromandaX-没错,但这是一个有很多困惑的问题。在问题的开头有这些信息会节省我很多时间阅读:)。顺便说一句,我刚刚在这里发布了与跨域弹出窗口加载和postMessage相关的内容:我想你可能误解了我的问题。当当前窗口和弹出窗口的来源不同时,可能无法使用“window.opener.data”,对吗?正确。使用window.open()打开具有不同域的url时,您无法访问弹出窗口中的window.opener。您将获得一个跨域安全异常。此示例不起作用,它假定源URL相同。