Getting a reference to the parent IFRAME

2019-02-17 14:00发布

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

2条回答
神经病院院长
2楼-- · 2019-02-17 14:23

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.)

查看更多
疯言疯语
3楼-- · 2019-02-17 14:27

I use this:

function get_container_iframe()
         {var rtn_iframe=null;
          var iframes=window.parent.document.getElementsByTagName('iframe');
          for (var i=0; i<iframes.length; ++i)
              {try
                   {var d=iframes[i].contentDocument || iframes[i].contentWindow.document || iframes[i].document; //ie | firefox etc | ie5
                    if (d===window.document)
                       {rtn_iframe=iframes[i];
                        break;
                       }
                   }
               catch(e) {}
              }
          return rtn_iframe;
         }
查看更多
登录 后发表回答