mr.boyfox mr.boyfox - 2 years ago 288
Javascript Question

How to set HTML content into an iframe

I have a HTML string

<body>Hello world</body>

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






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>
<script type="text/javascript" src="jquery_1.7.0.min.js"/>
<script type="text/javascript">
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;
<p>This is iframe:
<iframe id="iframe1">
<p>Your browser does not support iframes.</p>

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download