簡體   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