Accessing the document object of a frame with JavaScript

Brigand picture Brigand · Feb 18, 2013 · Viewed 56.4k times · Source

I'm testing on this page, and I'm not sure what I'm missing.

// Two frames on the page
> document.getElementsByTagName("frame").length
2

// Same domain, so no security restrictions
> document.getElementsByTagName("frame")[0].src
"http://www.quackit.com/html/templates/frames/menu_1.html"
> window.location.href
"http://www.quackit.com/html/templates/frames/frames_example_1.html"

// Can't access the document
> document.getElementsByTagName("frame")[0].document
undefined

It seems like this should work, so what's the problem? It needs to work in IE8, but I'm also testing in Chrome (newest stable).

Answer

Ian picture Ian · Feb 18, 2013

The all-around way to getting a frame's contents is with something like this:

var theFrame = document.getElementsByTagName("frame")[0];
var theFrameDocument = theFrame.contentDocument || theFrame.contentWindow.document;
var button = theFrameDocument.getElementById("mybutton");

However, it is possible to get a <frame>'s document by using its name, like:

window.frames["frame_name"].document

if the HTML were:

<frame name="frame_name">...</frame>