I’ve looked for a cross-browser way to programmatically set the innerHTML of an IFrame. (As in http://roneiv.wordpress.com/2008/01/18/get-the-content-of-an-iframe-in-javascript-crossbrowser-solution-for-both-ie-and-firefox/). I’ve written some sample code (below), and I can get it to work in Safari and Chrome, but not Firefox. Can anyone help me figure out what I need to do instead (in a portable way)?
<html>
<body>
<div name=FRAME2div id=FRAME2div style="position:absolute; background-color:blue; color:black; border-color:black;border-width:0; left:100px; top:40px; width:200px; height:200px; overflow:scroll; display:block; " >
</div>
<script type="text/javascript">
document.getElementById("FRAME2div").innerHTML = '<iframe border=0 id=IFRAME2 name=IFRAME2 ></iframe>';
document.getElementById("IFRAME2").contentWindow.document.body.innerHTML = '<html><body><p>NETSCAPE</p></body></html>';
</script>
</body>
</html>
In Firefox, the frame’s content seems to not be recognised when no initial content has been set. The easiest method to solve this, is shown in the code below:
Another method consists of setting the
srcproperty tojavascript:" ", and register an one-time load event handler. This method is slightly more complex, hence I do not describe it in a deeper detail.Every frame’s window object can be accessed through the
frameobject, by name.So, I recommend to use the following code:
document.documentElementrefers to the root element of a document, usually<html>. It’s possible that thebodyproperty ofdocumentisn’t ready yet, when you call your current code. By referring to the root element, this problem is circumvented.