Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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><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.

like image 771
Mr newt Avatar asked Aug 02 '16 21:08

Mr newt


2 Answers

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();
like image 92
Alexander O'Mara Avatar answered Oct 02 '22 17:10

Alexander O'Mara


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/

like image 32
Hacktisch Avatar answered Oct 02 '22 17:10

Hacktisch