Loading a string if HTML into an iframe using Java

2020-07-11 06:14发布

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.

3条回答
太酷不给撩
2楼-- · 2020-07-11 06:47

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/

查看更多
虎瘦雄心在
3楼-- · 2020-07-11 06:51

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>

查看更多
戒情不戒烟
4楼-- · 2020-07-11 07:04

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();
查看更多
登录 后发表回答