6

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.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
Mr newt
  • 63
  • 1
  • 1
  • 4
  • Yes with data uri, it's possible. – Adam Azad Aug 02 '16 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 Aug 03 '16 at 04:13
  • See this [answer](https://stackoverflow.com/a/16557787/7794769) which uses `iframe.contentWindow.document.write("Hello world")` – stomy Jun 19 '19 at 06:28

3 Answers3

6

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();
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • From where do you get that `srcdoc & src` is **asyncronous**? – stomy Jun 19 '19 at 06:39
  • @stomy I'm not sure if it's technically specified somewhere that it must be either synchronous or asynchronous, but it has been my experience that srcdoc and src (even with a daraURI) are asynchronous. – Alexander O'Mara Jun 19 '19 at 21:30
4

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/

Hacktisch
  • 1,392
  • 15
  • 33
3

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>
Adam Azad
  • 11,171
  • 5
  • 29
  • 70