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