Skip to content
Advertisement

Creating an iframe with given HTML dynamically

I’m trying to create an iframe from JavaScript and fill it with arbitrary HTML, like so:

var html = '<body>Foo</body>';
var iframe = document.createElement('iframe');
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);

I would expect iframe to then contain a valid window and document. However, this isn’t the case:

> console.log(iframe.contentWindow);
null

Try it for yourself: http://jsfiddle.net/TrevorBurnham/9k9Pe/

What am I overlooking?

Advertisement

Answer

Setting the src of a newly created iframe in javascript does not trigger the HTML parser until the element is inserted into the document. The HTML is then updated and the HTML parser will be invoked and process the attribute as expected.

http://jsfiddle.net/9k9Pe/2/

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
document.body.appendChild(iframe);
console.log('iframe.contentWindow =', iframe.contentWindow);

Also this answer your question it’s important to note that this approach has compatibility issues with some browsers, please see the answer of @mschr for a cross-browser solution.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement