set innerHTML of an iframe

∥☆過路亽.° 提交于 2019-12-17 17:53:11

问题


In javascript, how can I set the innerHTML of an iframe? I mean: how to set, not get.

window["ifrm_name"].document.innerHTML= "<h1>Hi</h1>" does not work, and the same for other solutions.

Iframe and parent document are on the same domain.

I would need to set html of the whole document iframe, not its body.

I would need to avoid jquery solution.


回答1:


A really simple example ...

<iframe id="fred" width="200" height="200"></iframe>

then the following Javascript is run, either inline, part of an event, etc ...

var s = document.getElementById('fred');
s.contentDocument.write("fred rules");

the "contentDocument" is the equivalent of the "document" you get in the main window, so you can make calls against this to set the body, head, any elements inside ... etc.

I've only tested this in IE8, Chrome and Firefox ... so you may want to test in IE6/7 if you have copies available.




回答2:


In Firefox and Chrome (don't know about Opera), you can use the data: URI scheme.

 <iframe src=".... data: URI data here ......">

JSFiddle example

Here is a tool to generate data:URI encoded data.

This does not work in IE:

For security reasons, data URIs are restricted to downloaded resources. Data URIs cannot be used for navigation, for scripting, or to populate frame or iframe elements.

If however as you say in the comment, getting/setting the document's body is enough, you are much easier off using one of the linked examples.




回答3:


In improving my file uploads in an AJAXS env I had the same need. This worked for me in ie8 and ff 22.0. Both the body innerhtml and div innerhtml work.

function copyframedata(data) {
  var x = document.getElementById("photo_mgr_frame");
  var y = x.contentWindow || x.contentDocument;
  if (y.document) y = y.document;
  y.getElementById('photo_mgr_mb').innerHTML = data;
}

got it from w3




回答4:


There is also the srcdoc attribute:

<iframe srcdoc="<p><h1>Hello</h1> world</p>"></iframe>

Demo, Polyfill.



来源:https://stackoverflow.com/questions/5050380/set-innerhtml-of-an-iframe

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