[英]javascript in iframe document.write overwrites parents document
I want to load HTML as string into an iframe
via Javascript. 我想通过Javascript将HTML作为字符串加载到
iframe
。 like this: 像这样:
$('#iframe1').contents().find('html').html("<h1>This is an iframe</h1>");
this worked great until I found out, that inside this HTML upcomming Javascript like document.write
are writing to the wrong document -> the parent! 直到我发现,在这种HTML向上的Javascript之类的
document.write
它们正在写入错误的文档->父文档!
Here is a Plunker to show it: http://plnkr.co/edit/YQAqqSDCVKnP3uhLj4lF?p=preview 这是一个显示它的柱塞: http ://plnkr.co/edit/YQAqqSDCVKnP3uhLj4lF?p=preview
if I load the same HTML to the iframe
via src as external document, the document.write
goes to the iframe
(and not to the parent), which is what i was expecting. 如果我通过src将相同的HTML作为外部文档通过src加载到
iframe
,则document.write
将转到iframe
(而不是父document.write
),这正是我所期望的。
Are there some insights out there? 有一些见解吗? How can I tell the browser to correctly create the iframes document scope before it executes its Javascript?
如何告诉浏览器在执行Javascript之前正确创建iframe文档作用域?
PS: Its meant to be for preview purposes, so i inject HTML-Code of a (trusted!) source, but within that code, document.write is allowed. PS:其目的是为了预览,因此我注入了(可信任!)源的HTML代码,但在该代码中允许document.write。
Ok. 好。
srcdoc
is helpfull here. srcdoc
在这里srcdoc
。
$('#iframe1').attr({srcdoc:intrusiveHTML});
I updated the Plunker. 我更新了Plunker。
With srcdoc
, Javascript won't slip up with the document scope. 使用
srcdoc
,Javascript不会随文档范围而滑落。
It won't work in IE ( http://caniuse.com/#feat=iframe-srcdoc ), so it might help to use Polyfill additionally: https://github.com/jugglinmike/srcdoc-polyfill 它在IE中不起作用( http://caniuse.com/#feat=iframe-srcdoc ),因此另外使用Polyfill可能会有所帮助: https : //github.com/jugglinmike/srcdoc-polyfill
But I did not test that yet. 但是我还没有测试。
Instead of using document.write
, use document.getElementById('iframe1').contentWindow.document.write
. 代替使用
document.write
,而使用document.getElementById('iframe1').contentWindow.document.write
。 Because when you point document it will take main window document, so we need to indicate which iframe doument need to be used. 因为当您指向文档时它将获取主窗口文档,所以我们需要指出需要使用哪个iframe副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.