问题
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. I would normally use a data: URI, but IE blocks this.
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. 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.
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? I also do not want to have to set the content from an external page.
回答1:
javascript:
is a kind of weird URI protocol. 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. (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.)
To write content into an IFRAME, get a reference to the frame's document and write to it. Doing so will require that you set the allow-same-origin
sandbox flag.
<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/
回答2:
HTML5 defines the "srcdoc" attribute for this purpose
<iframe seamless sandbox srcdoc="<p>Yeah, you can see it <a href="/gallery?mode=cover&amp;page=1">in my gallery</a>."></iframe>
来源:https://stackoverflow.com/questions/21587846/how-to-create-iframe-content-using-javascript-in-a-sandboxed-iframe-ie11