javascript 在 iframe document.write 中覆盖父文档

javascript in iframe document.write overwrites parents document

我想通过 Javascript 将 HTML 作为字符串加载到 iframe 中。 像这样:

$('#iframe1').contents().find('html').html("<h1>This is an iframe</h1>");

在我发现这个 HTML upcomming Javascript 像 document.write 正在写入错误的文档 -> 父文档之前,这非常有效!

这是一个 Plunker 来展示它: http://plnkr.co/edit/YQAqqSDCVKnP3uhLj4lF?p=preview

如果我通过 src 将相同的 HTML 作为外部文档加载到 iframe,则 document.write 会转到 iframe(而不是父文档),这正是我所期待的。

有什么见解吗? 我如何告诉浏览器在执行 Javascript 之前正确创建 iframe 文档范围?


PS:它是为了预览目的,所以我注入了 HTML-(可信!)来源的代码,但在该代码中,document.write 是允许的。

不使用 document.write,而是使用 document.getElementById('iframe1').contentWindow.document.write。 因为点document的时候会带main window document,所以我们需要指明需要使用哪个iframe文件。

好的。 srcdoc 在这里很有帮助。

$('#iframe1').attr({srcdoc:intrusiveHTML});

我更新了 Plunker。

有了 srcdoc,Javascript 就不会在文档范围内出错。

它在 IE 中不起作用 (http://caniuse.com/#feat=iframe-srcdoc),因此额外使用 Polyfill 可能会有所帮助: https://github.com/jugglinmike/srcdoc-polyfill

但我还没有测试。