繁体   English   中英

使用postMessage API时如何确保弹出窗口已完全加载?

[英]how to make sure that a popup window is fully loaded when using postMessage API?

如您所知,使用html5的API postMessage,我们可以将消息发布到当前页面的iframe或新的弹出窗口中,但是如果我们这样编码:

var popwindow = window.open('http://localhost:8080/index2.html');
popwindow.postMessage({"age":10}, 
   'http://localhost:8080/index2.html');

当弹出窗口尚未加载时,由于使用“ postMessage”,我们将不会收到消息,那么如何确定弹出窗口已加载? 我们不能在当前页面中使用popwindow.onload,那怎么办? 请帮助我〜谢谢

你可以Alwyas使用

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);
});

您不需要使用postMessage API来以这种方式使用弹出窗口。

//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? https://developer.mozilla.org/en-US/docs/Web/API/Window/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");

这种方法的一个缺点是sessionStorage对于HTTPS页面是单独的,因此您不能在这两个协议之间发送sessionStorage数据!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM