I\'m trying to figure out the best way to access an element\'s
window
and document
properties from a parent page. The <
During the time I made many tests, and finally came up with this short but robust syntax which works on every browser I could test:
var doc = iframe.contentDocument ?
iframe.contentDocument : (iframe.contentWindow.document || iframe.document);
EDIT: @DaggNabbit noticed that a reference error in iframe.contentWindow.document
, if iframe.contentWindow
is not set, would block the code execution, not allowing iframe.document
to be returned.
So I refined my code:
var doc = iframe.contentDocument ?
iframe.contentDocument :
(iframe.contentWindow ? iframe.contentWindow.document : iframe.document);
NOTE: iframe.document
is a workaround for IE5.
There's an easier way that's been around longer... use window.frames
to get a reference to the frame's window object.
By name or id:
var iframe_doc = window.frames.my_iframe.document;
or if you prefer:
var iframe_doc = window.frames['my_iframe'].document;
or by index:
var iframe_doc = window.frames[0].document;
Good reference for window.frames
here: http://developer.mozilla.org/en/DOM/window.frames
An excerpt:
each item in the window.frames pseudo-array represents the window object corresponding to the given <frame>'s or <iframe>'s content, not the (i)frame DOM element (i.e. window.frames[ 0 ] is the same thing as document.getElementsByTagName( "iframe" )[ 0 ].contentWindow)
all of the modern browsers except Chrome support both iframereference.contentWindow
and iframereference.contentDocument
, but only if the page opened in the iframe is on the same domain as the page containing the iframe.
To include Chrome, use var iwin=iframereference.contentWindow,
idoc=iwin.document;
.contentDocument
is the window.document
of the page in the iframe,
as is contentWindow.document
, but not .contentDocument.document
.
Chrome may include support for .contentDocument
in some future version- I hope so, because it is also the way all the other browsers find the document contained in an Object element, type text/html
, where the data attribute is the url of an html page.
i think this is a very easy and cross browser way
//get document object of IFRAME
if(typeof frame.contentDocument!='undefined') {
iframeDocument=frame.contentDocument;
} else {
iframeDocument=frame.document;
}
//get window object of IFRAME
if(typeof frame.contentWindow!='undefined') {
iframeWindow=frame.contentWindow;
} else {
iframeWindow=frame.window;
}
you can test it