如何将postMessage发布到同级iFrame [英] How do I postMessage to a sibling iFrame
问题描述
我正在寻找一种方法将postMessage发送到兄弟iFrame,而父页面中没有任何javascript。我遇到的困难是试图从第一个iFrame获取其他iFrame的窗口对象
I'm looking for a way to postMessage to a sibling iFrame without any javascript in the parent page. The difficulty I'm having is trying to get the window object for the other iFrame from the first iFrame
该页面的布局如下:
html body (http://host.com/)
iFrame#a (http://me.com/a)
iFrame#b (http://me.com/b)
来自 iFrame #a
我正在尝试:
(iFrame#b window).postMessage(...)
问题是我不知道如何获得窗口 iFrame#b
的对象来自 iFrame#a
。 parent.getElementById()
和其他函数受XSS限制。我只想向父网页上来自我的域 http://me.com/ $的所有其他iFrame发出
postMessage
上面的示例中的c $ c>。
The problem is I don't know how to get the window object for iFrame#b
from within iFrame#a
. parent.getElementById()
and other functions are subject to XSS restrictions. I just want to emit a postMessage
to all other iFrames on the parent page that are from my domain http://me.com/
in the example above.
推荐答案
虽然确实无法与其他窗口/ iframe交互在另一个域上, 可以获得对这样的窗口/ iframe的引用以及嵌入到该窗口/ iframe中的所有子iframe。这样做的方法是使用 window.top.frames
(访问顶部窗口对象)或 window.parent.frames
(访问直接父窗口对象,而可能有其他更高级别的祖先)。无需使用 getElementById
或其他与DOM相关的功能。有关详细信息,请参阅此处: https://developer.mozilla.org/en -US / docs / DOM / window.frames
While it is true that it is not possible to interact with another window/iframe that is on another domain, it is possible to get references to such a window/iframe and all the child iframes embedded into that window/iframe. The way to do it is to use window.top.frames
(to access the top window object) or window.parent.frames
(to access the direct parent window object, while there may be other higher-level ancestors). No need to use getElementById
or other DOM-related function. See this for more info: https://developer.mozilla.org/en-US/docs/DOM/window.frames
window.frames属性返回一个类似于数组的对象,然后你可以迭代并执行postMessage在每个iframe上。这不会触发相同来源的限制,因为除了在它们上使用postMessage之外,您不会以任何方式与任何窗口进行交互。由于您想在特定域的每个iframe上执行postMessage,您可以这样做:
The window.frames property returns an array-like object which you can then iterate over and do a postMessage on each iframe. This will not trigger the same-origin restrictions since you are not interacting with any window in any way except than using postMessage on them. Since you want to do a postMessage on every iframe from a specific domain, you can just do:
var frames = window.parent.frames;
for (var i = 0; i < frames.length; i++) {
frames[i].postMessage("hello", targetDomain);
}
这篇关于如何将postMessage发布到同级iFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!