动态创建具有给定 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);
空
> 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屋!