2014-09-25 71 views
0

我正在开发使用Worklight(混合技术)的Windows平板电脑/手机应用程序。我的应用程序中有jQuery,angular JS和WinJs。我需要在页面和它的子iframe之间进行通信。但获得错误“权限被拒绝”。我尝试了CONTENTWINDOW,CONTENTDOCUMENT,PARENT,TOP.XXXX场景,但获得了“许可拒绝”。 POSTMESSAGE概念也不起作用。使用WinJS在windows phone/tablet中进行跨域通信

父母与孩子(IFRAME)之间有任何沟通的方式。实际上,PARENT和IFRAME的域名显示相同(应用程序ID显示为域名)。

回答

1

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引发事件的应用程序,如果这是有用的。如果你想知道为什么起源需要保持原样,那么在后面的文档中有详细信息和链接。

+0

谢谢你Kraig – Theja 2014-10-09 11:48:37

+0

window.parent让访问被拒绝。有没有解决方法? – shifu 2014-12-01 14:31:20

+0

我在访问iframe内容窗口时发送“拒绝访问权限”以发布消息 - var iframe = document.getElementById(“Map”)。contentwindow – Kanchan 2016-11-23 13:29:07