PostMessage有效,但您需要在应用程序代码和iframe中正确设置原点。我在免费电子书第012章中展示的例子Programming Windows Store Apps with HTML, CSS, and JavaScript, 2nd Edition就是这样做的。这里有一个总结:
首先,这里是在应用程序的default.html中的iframe标记:
<iframe id="map" src="ms-appx-web:///html/map.html" aria-label="Map"></iframe>
其中map.html是我的包,但在网络环境中运行的课程。
要PostMessage的从应用到的iframe,产地必须是MS-APPX的web加主机页面:
frame.postMessage(message, "ms-appx-web://" + document.location.host);
的iframe内,验证的起源是这样的:
window.addEventListener("message", processMessage);
function processMessage(msg) {
//Verify data and origin (in this case the local context page)
if (!msg.data || msg.origin !== "ms-appx://" + document.location.host) {
return;
}
//Message is from the app, process with confidence.
}
要发布来自iframe来应用:
window.parent.postMessage(message, "ms-appx://" + document.location.host);
并处理它的应用程序:
window.addEventListener("message", processFrameEvent);
function processFrameEvent (message) {
//Verify data and origin (in this case the web context page)
if (!message.data || message.origin !== "ms-appx-web://" + document.location.host) {
return;
}
//Message is from iframe.
}
书中的代码有一些通用的代码中使用的postMessage调用在iframe代码的事件,并从IFRAME引发事件的应用程序,如果这是有用的。如果你想知道为什么起源需要保持原样,那么在后面的文档中有详细信息和链接。
谢谢你Kraig – Theja 2014-10-09 11:48:37
window.parent让访问被拒绝。有没有解决方法? – shifu 2014-12-01 14:31:20
我在访问iframe内容窗口时发送“拒绝访问权限”以发布消息 - var iframe = document.getElementById(“Map”)。contentwindow – Kanchan 2016-11-23 13:29:07