Cannot set document.body.innerHTML of IFrame in Firefox

▼魔方 西西 提交于 2019-12-04 04:50:52

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:

//Note: ID is not necessary for this example
document.getElementById("FRAME2div").innerHTML = '<iframe id=IFRAME2 name=IFRAME2 ></iframe>';
var doc = frames["IFRAME2"].document;

//Trigger a page "load".
doc.open();
doc.close();
//Set innerHTML of the body tag.
doc.body.innerHTML = '<p>NETSCAPE</p>';

Another method consists of setting the src property to javascript:"&nbsp;", 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 frame object, by name.

So, I recommend to use the following code:

frames['IFRAME2'].document.documentElement.innerHTML = "<body>...</body>";

document.documentElement refers to the root element of a document, usually <html>. It's possible that the body property of document isn't ready yet, when you call your current code. By referring to the root element, this problem is circumvented.

You're setting the innerHTML while there's an in-flight about:blank load for the iframe. When that finishes loading, it replaces the document you modified.

If you do your modification off the iframe's onload it will work in all browsers.

I tested this code with firefox and ie and it works. You must wait the completion of page load before modify contents. I used the load event of body.

<html> 
<head>
<script type="text/javascript"> 
var Fill_Iframe=function(){document.getElementById("IFRAME2").contentWindow.document.body.innerHTML = '<p>testo</p>';}; 
</script>
</head>

<body onload="Fill_Iframe()"> 

<iframe name="IFRAME2" id="IFRAME2" > 
</iframe> 

</body> 
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!