PostMessage 有效,但您需要在应用代码和 iframe 中正确设置来源。我在免费电子书的第 2 章中展示的示例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 在我的包中,但在网络环境中运行,当然。
要从应用程序到 iframe 的 PostMessage,来源必须是 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 向应用程序引发事件(如果有用的话)。如果您想知道为什么源需要保持原样,那么该章节中也有详细信息和指向背景文档的链接。