19

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

Boaz
  • 19,892
  • 8
  • 62
  • 70
Brigand
  • 84,529
  • 20
  • 165
  • 173
  • 4
    Are you actually using frames in 2013, or are those iFrames ? – adeneo Feb 18 '13 at 20:26
  • 1
    What about `document.getElementsByTagName("frame")[0].contentDocument`? – Felix Kling Feb 18 '13 at 20:27
  • `var frame = document.getElementsByTagName("frame")[0]; var frame_doc = frame.contentWindow.document || frame.contentDocument;` - then use `frame_doc` as the frame's document – Ian Feb 18 '13 at 20:33
  • possible duplicate of [Getting the document object of an iframe](http://stackoverflow.com/questions/7570496/getting-the-document-object-of-an-iframe) – Veger Feb 19 '13 at 08:37

2 Answers2

39

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>
Ian
  • 50,146
  • 13
  • 101
  • 111
1

You could use

parent.frame.location.href = ...

Where frame is the name/id of the frame you d like to change.

Greets Marc

mooonli
  • 2,355
  • 4
  • 23
  • 32