mr.boyfox mr.boyfox - 7 months ago 55
Javascript Question

How to set HTML content into an iframe

I have a HTML string

<html>
<body>Hello world</body>
</html>


and I want to set it to an iframe with JavaScript. I am trying to set the HTML like this:

contentWindow.document.body.innerHTML


or

contentDocument.body.innerHTML


or

document.body.innerHTML


but IE gives "Access is denied." or "Object does not support this property or method." or "Invalid final element to the action." errors.

Here is my full code:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery_1.7.0.min.js"/>
<script type="text/javascript">
$(document).ready(function(){
var htmlString = "<html><body>Hello world</body></html>";
var myIFrame = document.getElementById('iframe1');
// open needed line commentary
//myIFrame.contentWindow.document.body.innerHTML = htmlString;
//myIFrame.contentDocument.body.innerHTML = htmlString;
//myIFrame.document.body.innerHTML = htmlString;
//myIFrame.contentWindow.document.documentElement.innerHTML = htmlString;
});
</script>
</head>
<body>
<p>This is iframe:
<br>
<iframe id="iframe1">
<p>Your browser does not support iframes.</p>
</iframe>
</body>
</html>

Answer

You could use:

document.getElementById('iframe1').contentWindow.document.write("<html><body>Hello world</body></html>");

Here's a jsFiddle, which works in all major browsers.

Note that instead of contentDocument.write you should use contentWindow.document.write: this makes it work in IE7 as well.

Comments