13

I have an IFRAME that should be filled with content from JavaScript. Had the content be on the server all I had to do is:

    function onIFrameFill() {
         myIframe.location.href = "HelloWorld.html";
     }

But the content I have is a HTML page generated on the client and represented as a string (I have not much influence on it). How can I populate the content of the my iframe programatically?

user256890
  • 3,396
  • 5
  • 28
  • 45

4 Answers4

24

I think you're looking for something like:

var iframeDoc = myIframe.contentWindow.document;
iframeDoc.open();
iframeDoc.write('hello world');
iframeDoc.close();
Jeffery To
  • 11,836
  • 1
  • 27
  • 42
  • 1
    For me in Chrome Version 41.0.2272.76 m if you don't open() the iframeDoc first, then it will *append* the text; if you open() it clears out the iframeDoc and *overwrites* the text. You can write('bold') and the HTML will be interpreted as a tag. – Nate Anderson Mar 04 '15 at 18:26
  • What about Chrome complaining about document.write()? [Violation] Avoid using document.write(). https://developers.google.com/web/updates/2016/08/removing-document-write This seems like a legitimate use, since I'm not injecting scripts. Still it would be nice not to have "Violation" appear in the console – BrianK Dec 17 '20 at 16:43
  • @BrianK Using `document.write()` isn’t recommended for performance reasons. I believe I gave this answer because it most directly addressed OP’s question. It would be better to set `iframe.contentWindow.location.href` to a page and then have that page make DOM changes. – Jeffery To Dec 24 '20 at 11:00
4

Tried setting .innerHTML but that does not work. Solution by Jeffery To works. Just want to add that myIframe.contentWindow might not work in old browsers (read IE old versions) so you can do

var iFrameWindow = myIframe.contentWindow || myIframe.documentWindow;
var iFrameDoc = iFrameWindow.document;

then use the document open(), write() & close() as above.

Agraj
  • 466
  • 5
  • 19
1

Similar to Jeffry but using contentDocument instead.

let iframe = document.querySelector('iframe');
let doc = iframe.contentDocument;
doc.open();
doc.write('Hello world!');
doc.close();
Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
  • 2
    Instead of `document.write()` you could now use a new attribute on iframe which is srcDoc. https://caniuse.com/iframe-srcdoc – Fasani Aug 12 '21 at 08:04
0

What about .innerHTML?

myIframe.innerHTML = "This is some HTML <b>text</b>";
Luca Matteis
  • 29,161
  • 19
  • 114
  • 169