Javascript Reference - HTML DOM IFrame contentWindow Property








The contentWindow property returns the Window object generated by an iframe element.

Browser Support

contentWindow Yes Yes Yes Yes Yes

Syntax

var i = iframeObject.contentWindow 

Return Value

A reference to the window object.

Example

The following example shows how to access the document of an iframe to change the background color.


<!DOCTYPE html>
<html>
<body>
<iframe id="myframe" src="http://example.com"></iframe>
<p id="demo"></p>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--  ww  w  .  jav a2s  .  c  o  m-->
    var x = document.getElementById("myframe");
    var y = x.contentWindow.document;
    y.body.style.backgroundColor = "red";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

Another example on how to change the background color of the document contained in an iframe.


<!DOCTYPE html>
<html>
<body>
<iframe id="myframe" src="http://example.com"></iframe>
<p id="demo"></p>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from   www  .j av a  2  s. c  o  m-->
    var x = document.getElementById("myframe");
    var y = (x.contentWindow || x.contentDocument);
    if (y.document) y = y.document;
    y.body.style.backgroundColor = "red";
}
</script>
</body>
</html>

The code above is rendered as follows: