簡體   English   中英

使用跨域的postMessage將iframe傳遞給父級

[英]Iframe to parent using postMessage for cross domains

即使在網上和在本網站上閱讀了其他帖子后,我也無法使用postMessage。

我有一個使用var abc_iframe = document.createElement('iframe')生成的iframe。 根據我的理解,我想為此附加一個事件偵聽器,以偵聽iframe中的消息。 我努力了:

1. abc_iframe.addEventListener("message", function(e){ console.log(e.data); }, false);
2. document.frames['id_iframe'].addEventListener("message", function(e){ console.log(e.data); }, false); 
(id_iframe right here being the id of the iframe)
3. WinJS.Application.addEventListener("message", function(e){ console.log(e.data); }, false);

這些都不起作用。 我正在使用從iframe中發送postMessage

1. parent.postMessage("message", "ms-appx://" + document.location.host);
2. window.parent.postMessage("message", "ms-appx://" + document.location.host);

iframe內容托管在另一個域(非本地)上。

您需要附加到窗口對象(而不是iframe)以接收來自iframe的消息。

window.addEventListener(function(e) {}));

在您發送的消息中,您應該包含一些信息,以便父​​級識別發送消息的iframe,因為來自所有窗口的所有消息都將由此事件處理程序處理。

還要注意,addEventListener僅在某些瀏覽器中有效。 較舊的IE版本使用attachEvent。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM