得到父IFRAME的引用 [英] Getting a reference to the parent IFRAME
问题描述
请注意,没有上下文信息可用(例如,window.xxx等解决方案将无法使用) - 所有可用的
感谢
文档不直接连接到其父文档。您需要参考窗口
才能拿起父母
。
DOM Level 2 Views属性 document.defaultView
将在大多数现代网络浏览器中为您提供窗口
,但在IE中使用非标准的 document.parentWindow
。 (某些较旧或更晦涩的浏览器不实现这些属性之一,在这种情况下您将被卡住。)
这将给您窗口
的父文档。如果您想获取保存文档的< iframe>
,则必须遍历页面上的所有iframe,并检查所包含的文档是否为您自己。
再次,从iframe元素返回到孩子的方法在IE中是无可比拟的( iframe.contentWindow
给你窗口
)与DOM标准和其他所有人( iframe.contentDocument
给你文件
)。
所以,像:
function getFrameForDocument(document){
var w = document.defaultView || document.parentWindow;
var frames = w.parent.document.getElementsByTagName('iframe');
for(var i = frames.length; i - > 0;){
var frame = frames [i];
尝试{
var d = frame.contentDocument || frame.contentWindow.document;
if(d === document)
return frame;
} catch(e){}
}
}
( try ...
是为了避免在由于另一个iframe位于不同域中导致文档访问失败时导致循环,导致同源策略错误。 / p>
Say I have a reference to a document object, which is contained inside an IFRAME. How do I get a reference to the container IFRAME? .parentNode and .ownerDocument both return null.
Please note that no context information is available (e.g. solutions like 'window.xxx' will not work) - all that's available is a reference to the document object.
Thanks
A document is not directly connected to its parent document. You do need a reference to window
in order to pick up the parent
.
The DOM Level 2 Views property document.defaultView
will give you the window
in most modern web browsers, but in IE you have to use the non-standard document.parentWindow
instead. (Some older or more obscure browsers don't implement either of these properties, in which case you're stuck.)
That'll give you the window
of the parent document. If you want to get the <iframe>
that holds your document, you'll have to iterate through all the iframes on the page and check whether the contained document is yourself.
Again, the method to get from an iframe element back to the child is gratuitously different in IE (iframe.contentWindow
giving you the window
) vs the DOM standard and everyone else (iframe.contentDocument
giving you the document
).
So, something like:
function getFrameForDocument(document) {
var w= document.defaultView || document.parentWindow;
var frames= w.parent.document.getElementsByTagName('iframe');
for (var i= frames.length; i-->0;) {
var frame= frames[i];
try {
var d= frame.contentDocument || frame.contentWindow.document;
if (d===document)
return frame;
} catch(e) {}
}
}
(The try...
is to avoid crashing the loop out when a document access fails due to another iframe being on a different domain, causing a Same Origin Policy error.)
这篇关于得到父IFRAME的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!