简体   繁体   English

如何在沙盒iframe(IE11)中使用JavaScript创建iframe内容?

[英]How to create iframe content using javascript in a sandboxed iframe (IE11)?

I am attempting to build a testing page for use in Internet explorer by creating an iframe and dynamically building the iframe contents using javascript or vbscript. 我正在尝试通过创建iframe并使用javascript或vbscript动态构建iframe内容来构建供Internet Explorer使用的测试页。 I would normally use a data: URI, but IE blocks this. 我通常会使用数据:URI,但是IE会阻止它。

example. 例。

<iframe sandbox="allow-scripts" src="javascript:document.write('test')"></iframe>

it appears that IE is the only browser that will not allow me to build the iframe contents through a javascript:function() src, even though the allow-scripts sandbox attribute is set. 似乎IE是唯一一个不允许我通过javascript:function()src构建iframe内容的浏览器,即使设置了allow-scripts沙箱属性也是如此。 I am not trying to pass any information between the iframe and parent window and do not want to have the allow-same-origin set since it would pretty much defeat the purpose of having a sandboxed iframe. 我不想在iframe和父窗口之间传递任何信息,也不想设置allow-same-origin设置,因为它几乎破坏了具有沙盒iframe的目的。

Are there any other methods to dynamically build the iframe contents other than a javascript or data: URI in the src, or through javascript in the parent window since it will not work with the sandboxed iframe due to same origin restrictions? 除了JavaScript或数据外,是否还有其他方法可以动态构建iframe内容:src中的URI,或通过父窗口中的javascript通过URI,因为由于相同的来源限制,它无法与沙盒iframe一起使用? I also do not want to have to set the content from an external page. 我也不想从外部页面设置内容。

javascript: is a kind of weird URI protocol. javascript:是一种奇怪的URI协议。 It works in some contexts, like <a href> , but not all - for instance, a window's location can not be set to such a URI. 它可以在某些上下文中工作,例如<a href> ,但不是全部-例如,不能将窗口的位置设置为此类URI。 (While you can assign a javascript: URI to window.location as a really roundabout way of running a script, the window's location doesn't stay set to that value.) (虽然您可以为window.location分配一个javascript: URI作为运行脚本的一种真正的回旋方式,但窗口的位置不会保持设置为该值。)

To write content into an IFRAME, get a reference to the frame's document and write to it. 要将内容写入IFRAME,请获取对框架文档的引用并对其进行写入。 Doing so will require that you set the allow-same-origin sandbox flag. 这样做将要求您设置allow-same-origin沙箱标志。

<iframe id="myframe" sandbox="allow-scripts allow-same-origin" src="about:blank"></iframe>

var frame = document.getElementById("myframe");
var fdoc = frame.contentDocument;

fdoc.write("Hello world"); // or whatever

Live example: http://jsfiddle.net/wUvrF/1/ 实时示例: http//jsfiddle.net/wUvrF/1/

HTML5为此定义了“ srcdoc”属性

<iframe seamless sandbox srcdoc="<p>Yeah, you can see it <a href=&quot;/gallery?mode=cover&amp;amp;page=1&quot;>in my gallery</a>."></iframe>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM