Filling an IFRAME with dynamic content from JavaScript
Asked Answered
S

4

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?

Shellishellie answered 19/4, 2010 at 8:3 Comment(0)
H
24

I think you're looking for something like:

var iframeDoc = myIframe.contentWindow.document;
iframeDoc.open();
iframeDoc.write('hello world');
iframeDoc.close();
Hephzipa answered 19/4, 2010 at 8:17 Comment(3)
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('<em>bold</em>') and the HTML will be interpreted as a tag.Rodrique
What about Chrome complaining about document.write()? [Violation] Avoid using document.write(). developers.google.com/web/updates/2016/08/… This seems like a legitimate use, since I'm not injecting scripts. Still it would be nice not to have "Violation" appear in the consoleInviolate
@Inviolate 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.Hephzipa
U
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.

Undulatory answered 4/7, 2012 at 7:0 Comment(0)
M
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();
Maness answered 28/1, 2020 at 7:20 Comment(1)
Instead of document.write() you could now use a new attribute on iframe which is srcDoc. caniuse.com/iframe-srcdocMasturbation
L
0

What about .innerHTML?

myIframe.innerHTML = "This is some HTML <b>text</b>";
Lorelle answered 19/4, 2010 at 8:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.