Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set innerHTML of an iframe

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.

like image 442
tic Avatar asked Feb 19 '11 10:02

tic


People also ask

How do I get the inner HTML of iframe?

Assuming your iFrame is in the same domain as your OutSystems application you can run Javascript to get the values: var myIFrame = document. getElementById('<Widget.Id>'); //Fetch Inner HTML inside body var contentHTML = myIFrame. contentWindow.

How do I assign innerHTML?

To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.

Can you put HTML in an iframe?

An IFrame (Inline Frame) is an HTML document embedded inside another HTML document on a website. The IFrame HTML element is often used to insert content from another source, such as an advertisement, into a Web page.


3 Answers

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.

like image 109
Jeff Parker Avatar answered Oct 13 '22 02:10

Jeff Parker


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.

like image 23
Pekka Avatar answered Oct 13 '22 00:10

Pekka


There is also the srcdoc attribute:

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

Demo, Polyfill.

like image 26
nha Avatar answered Oct 13 '22 02:10

nha