13

If use following way to get the contentWindow, the value is undefined

<html>
<head>
    <title>iframe test</title>
</head>
<body>
    <iframe id="frame1" src="frame1.html" name="frame1"></iframe>
<script>
    document.body.onload = function() {
        console.info("index loaded");
        var frame1 = window.frames["frame1"];
        console.info(frame1.contentWindow);
    }
</script>
</body>
</html>

If use the other way like following, it works fine:

var frame1 = document.getElementById("frame1");
console.info(frame1.contentWindow);

I tested on FF 29.0.1, chrome 34, IE11, they all work the same way.

So I have two questions:

  1. why the first way can't get contentWindow value
  2. iframe.contentWindow is compatible in all browser?
jason
  • 1,621
  • 6
  • 21
  • 39

1 Answers1

18
window.frames["frame1"];

is the contentWindow, it gets a named window, and in your case it's the same thing as

document.getElementById("frame1").contentWindow

FIDDLE

isherwood
  • 58,414
  • 16
  • 114
  • 157
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • so contentWindow is compatible in all browsers includes IE8+? – jason May 17 '14 at 13:35
  • Should be pretty cross browser, some browser used to use contentDocument, but I think contentWindow works everywhere today. – adeneo May 17 '14 at 14:26