动态创建具有给定HTML的iframe [英] Creating an iframe with given HTML dynamically
问题描述
我正在尝试从JavaScript创建iframe并使用任意HTML填充它,如下所示:
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);
我希望 iframe
然后包含一个有效的窗口和文档。但是,情况并非如此:
I would expect iframe
to then contain a valid window and document. However, this isn't the case:
> console.log(iframe.contentWindow);
null
> console.log(iframe.contentWindow);
null
亲自尝试: http:// jsfiddle.net/TrevorBurnham/9k9Pe/
我在俯瞰什么?
推荐答案
在javascript中设置新创建的 iframe
的 src
不会触发HTML解析器元素插入到文档中。然后更新HTML并调用HTML解析器并按预期处理该属性。
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.
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);
这也回答了你的问题,重要的是要注意这种方法与某些浏览器存在兼容性问题,请参阅@mschr对跨浏览器解决方案的回答。
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.
这篇关于动态创建具有给定HTML的iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!