简体   繁体   English

使用JavaScript将HTML中的字符串加载到iframe中

[英]Loading a string if HTML into an iframe using JavaScript

I have a string of HTML tags that I can add to or change whenever I like. 我有一串HTML标签,我可以随时添加或更改。

"<html><body><script language="javascript" src=""></script></body></html>"

Is it possible to load that string at runtime into an Iframe as if it was an HTML file? 是否可以在运行时将该字符串加载到Iframe中,就像它是HTML文件一样?

This is for Construct 2. I have an object that can load HTML from a url fine, it can also insert HTML, and run scripts, but not as is. 这是针对Construct 2.我有一个对象可以从url加载HTML,它也可以插入HTML,并运行脚本,但不是原样。

Sure, there are a couple of different options. 当然,有几种不同的选择。

Via srcdoc (asyncronous): 通过srcdocsrcdoc ):

iframe.srcdoc = html;

Via data URI (asyncronous): 通过数据URI (异步):

iframe.src = 'data:text/html;charset=utf-8,' + escape(html);

Via document.write (syncronous, and works in really old browsers): 通过document.write (同步,并在真正的旧浏览器中工作):

var idoc = iframe.contentWindow.document;
idoc.write(html);
idoc.close();

With Data URI , ( see browser support ) it's possible. 使用Data URI ,( 参见浏览器支持 )是可能的。 The format as described is 所描述的格式是

data:[<mime type>][;charset=<charset>][;base64],<encoded data>.

You might not need to base64 encode your string unless the string has specific characters. 除非字符串具有特定字符,否则您可能不需要对字符串进行base64编码。 This Snippet fulfills your needs: 此代码段满足您的需求:

 var iframe = document.getElementById('iframe'), htmlStr = "<html><body><h1>Hell World</h1></body></html>"; iframe.src = 'data:text/html,'+htmlStr; 
 <iframe id="iframe" src="blank:"></iframe> 

You can do it with 你可以做到

document.getElementById('iframe').src = "data:text/html;charset=utf-8," + escape(html);

See the following fiddle for an example 有关示例,请参阅以下小提琴

https://jsfiddle.net/erk1e3fg/ https://jsfiddle.net/erk1e3fg/

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

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