Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a reference to the parent 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

like image 327
Melllvar Avatar asked Aug 28 '10 20:08

Melllvar


1 Answers

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

like image 109
bobince Avatar answered Oct 05 '22 23:10

bobince