获取对父IFRAME的引用 [英] Getting a reference to the parent IFRAME

查看:185
本文介绍了获取对父IFRAME的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个参考文件对象,它包含在IFRAME中。如何获得对容器IFRAME的引用? .parentNode和.ownerDocument都返回null。



请注意,没有上下文信息可用(例如'window.xxx'等解决方案将无法工作) - 所有可用的



感谢

解决方案

不直接连接到其父文档。您需要引用窗口才能获取



DOM第2级视图属性 document.defaultView 将在大多数新型网络浏览器中为您提供窗口必须使用非标准 document.parentWindow 。 (有些旧的或更模糊的浏览器不会实现这些属性,在这种情况下你会卡住。)



这将给你窗口。如果您要获取保存您的文档的< iframe> ,则必须遍历页面上的所有iframe,并检查所包含的文档是否为您自己。



再次,从iframe元素返回子元素的方法在IE中是无意的不同的( iframe.contentWindow 给你窗口)对DOM标准和其他人( iframe.contentDocument 给你<$ c $

 

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){}
}
}

try ... 是为了避免由于另一个iframe位于不同的域而导致文档访问失败时导致循环失败,从而导致同源策略错误。)


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆