来自同一域的两个 iframe 之间使用 postMessage 进行通信
我有两个来自同一域的 iframe,它们托管在另一个域的文档中。问题是这些 iframe 无法通过 postMessage 相互通信。我什至无法从 iframe2 访问 iframe1 的 DOM,即使它们属于同一域。有什么解决办法吗????
我使用以下选项来引用所需的 iframe。
parent.frame[x]
我尝试使用以下几行来访问 iframes
parent.frame[x].contentWindow returns null,
parent.frame[x].document.getElementsByTagName("body") returns null
Update 的 DOM:
我想我的问题还不够清楚。 postMessage api 没有问题,实际问题是浏览器在 iframe 文档周围创建一个自定义框架集,就我而言!
因此 parent.frame[x]
不会指向 iframe 窗口,而是指向 iframe 窗口内的自定义框架集。
下面的问题很好地解释了这个问题。
I have two iframes from the same domain, which are hosted in document from another domain. The problem is these iframes cannot communicate with each other through postMessage. I cant even access the DOM of iframe1 from iframe2 even though they belong to same domain. Is there any solution ????
I used following options to refer the required iframe.
parent.frame[x]
I tried following lines to access DOM of iframes
parent.frame[x].contentWindow returns null,
parent.frame[x].document.getElementsByTagName("body") returns null
Update:
I guess my question is not clear enough. There is no problem with postMessage api, the actual problem is browser creates a custom frameset around the iframe document, in my case!
So parent.frame[x]
won't point to the iframe window, instead it points to the custom frameset inside the iframe window.
Following question explains the problem well.
Prevent browser from loading a custom frameset in an iframe's document
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果需要跨窗口同域通信,可以通过
localStorage
进行设置。当您将项目添加到localStorage
时,您会在同一域的所有其他窗口/ iframe/选项卡中收到窗口"storage"
事件。因此,您基本上可以在一个 iframe 中使用
localStorage.setItem('name', 'value')
来监听window.addEventListener('storage', (event) => {/*处理消息 */})
然后你就得到了消息。If you want cross-window same-domain communication, you can set it up via
localStorage
. When you add an item tolocalStorage
, you get window"storage"
event in all other windows / iframes / tabs of the same domain.So, you basically
localStorage.setItem('name', 'value')
in one iframe while you listen towindow.addEventListener('storage', (event) => {/* handle message */})
and you get the message.查看以下对 postMessage 函数的描述以及如何使用它。因此,在第 1 帧中,您调用
postMessage
方法,在第 2 帧中,您订阅通知。显然你使用的浏览器必须支持这个API。还有一个非常好的 jQuery 插件,它包装了这个 API 并简化了其使用。它也可以在不支持
postMessage
方法的浏览器中使用 url 的哈希部分工作。Take a look at the following description of the postMessage function and how it could be used. So in frame1 you call the
postMessage
method and in frame2 you subscribe for notifications. Obviously the browser you are using must support this API.There's also a very nice jQuery plugin which wraps this API and simplifies its usage. It also works in browsers that do not support the
postMessage
method by using the hash portion of the url.