我可以使用window.postMessage方法从iframe中的网页通信到包括该iframe的UIWebView吗

Can I use the window.postMessage method to communicate from a webpage in an iframe out to the UIWebView that includes that iframe?

本文关键字:iframe 通信 网页 包括该 UIWebView 可以使 postMessage window 方法 我可以      更新时间:2024-04-12

我经常使用window.postMessage和"message"事件侦听器在父网页与其子IFRAME元素中的网页之间跨域通信。我想知道UIWebView及其子IFRAME元素中的网页是否可能实现这一点。

是的,这确实是可能的。几天前,我在自己的应用程序中对此进行了测试,并取得了成功。

在我想与之交流的网页上,我只是在窗口中添加了一个"消息"事件侦听器

在网页上收听UIWebView消息

window.addEventListener("message", onmessage, false);
window.onmessage = function(e){
    // e.data contains message
    // e.origin will equal NULL as theres no domain in UIWebView    
}

UIWebView只需要抓取嵌入的iFrame对象的窗口并在其上调用postMessage:

iFrameObject.contentWindow.postMessage("message", http://webpageDomain...);

相反,UIWebView中的html实现需要监听消息,就像上面的代码一样。这次e.origin将成为网页的域名。

网页只需要用*作为targetDomain调用以下内容,因为UIWebView没有。

parent.postMessage("message", *);