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

问题描述 投票:0回答:2

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

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

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

javascript html postmessage
2个回答
7
投票

你总是可以使用

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

1
投票

以这种方式使用弹出窗口不需要 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 数据!

© www.soinside.com 2019 - 2024. All rights reserved.