Iframe使用postMessage为跨域创建父级



我在使用postMessage时遇到了问题,即使在阅读了在线和本网站上的其他帖子后也是如此。

我有一个iframe,它是使用var abc_iframe=document.createElement('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。

最新更新