最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Loading a string if HTML into an iframe using JavaScript - Stack Overflow

programmeradmin1浏览0评论

I have a string of HTML tags that I can add to or change whenever I like.

"<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?

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.

I have a string of HTML tags that I can add to or change whenever I like.

"<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?

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.

Share Improve this question edited Aug 2, 2016 at 23:00 Alexander O'Mara 60.5k19 gold badges172 silver badges181 bronze badges asked Aug 2, 2016 at 21:58 Mr newtMr newt 731 gold badge1 silver badge4 bronze badges 3
  • Yes with data uri, it's possible. – Adam Azad Commented Aug 2, 2016 at 21:59
  • Unfortunately it looks like javascript will not work as I'm limited by the editor to what I can input into the script. I can add strings, just not properly formatted strings. – Mr newt Commented Aug 3, 2016 at 4:13
  • See this answer which uses iframe.contentWindow.document.write("<html><body>Hello world</body></html>") – stomy Commented Jun 19, 2019 at 6:28
Add a comment  | 

3 Answers 3

Reset to default 7

Sure, there are a couple of different options.

Via srcdoc (asyncronous):

iframe.srcdoc = html;

Via data URI (asyncronous):

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

Via document.write (syncronous, and works in really old browsers):

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

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/

With Data URI, (see browser support) it's possible. 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. 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>

发布评论

评论列表(0)

  1. 暂无评论