iframe document.write中的javascript覆盖父文档
我想通过Javascript将HTML作为字符串加载到iframe document.write中的javascript覆盖父文档,javascript,iframe,parent,document,document.write,Javascript,Iframe,Parent,Document,Document.write,我想通过Javascript将HTML作为字符串加载到iframe中。 像这样: $('#iframe1').contents().find('html').html("<h1>This is an iframe</h1>"); $('iframe1').contents().find('html').html(“这是一个iframe”); 这非常有效,直到我发现,在这个HTML升级Javascript中,像document.write正在向错误的文档->父级写入 下
iframe
中。
像这样:
$('#iframe1').contents().find('html').html("<h1>This is an iframe</h1>");
$('iframe1').contents().find('html').html(“这是一个iframe”);
这非常有效,直到我发现,在这个HTML升级Javascript中,像document.write
正在向错误的文档->父级写入
下面是一个Plunker来展示:
如果我通过src将相同的HTML加载到iframe
作为外部文档,则document.write
将转到iframe
(而不是父级),这是我所期望的
有什么见解吗?
我如何告诉浏览器在执行其Javascript之前正确创建iframes文档范围
PS:它是为了预览的目的,所以我插入了一个(可信!)源的HTML代码,但在该代码中,允许使用document.write。而不是使用
document.write
,使用document.getElementById('iframe1').contentWindow.document.write
。
因为当您指向文档时,它将使用主窗口文档,所以我们需要指出需要使用哪个iframe文档。确定
srcdoc
在此处提供帮助
$('#iframe1').attr({srcdoc:intrusiveHTML});
我更新了Plunker
使用srcdoc
,Javascript不会在文档范围内出错
它在IE()中不起作用,因此另外使用Polyfill可能会有所帮助:
但是我还没有测试它。不是我在使用document.write,它的html代码来自第三方,不在我的控制之下。srcdoc polyfill似乎工作得很好,尽管它不是解决问题的唯一方法,但它是一个向前看的方法,这是一个很好的提示。