Html code as IFRAME source rather than a URL

Max picture Max · May 23, 2011 · Viewed 161.5k times · Source

This standard code for an IFRAME, is there a way to replace the src URL with Just html code? so my problem is simple, I have a page it loads an HTML body from MYSQL I want to present that code in a frame so it renders it self independent of the rest of the page and in the confines of that specific bordering.

<iframe src="http://example.com" name="test" height="120" width="600">You need a Frames Capable browser to view this content.</iframe>   

Answer

lonesomeday picture lonesomeday · May 23, 2011

You can do this with a data URL. This includes the entire document in a single string of HTML. For example, the following HTML:

<html><body>foo</body></html>

can be encoded as this:

data:text/html;charset=utf-8,%3Chtml%3E%3Cbody%3Efoo%3C/body%3E%3C/html%3E

and then set as the src attribute of the iframe. Example.


Edit: The other alternative is to do this with Javascript. This is almost certainly the technique I'd choose. You can't guarantee how long a data URL the browser will accept. The Javascript technique would look something like this:

var iframe = document.getElementById('foo'),
    iframedoc = iframe.contentDocument || iframe.contentWindow.document;

iframedoc.body.innerHTML = 'Hello world';

Example


Edit 2 (December 2017): use the Html5's srcdoc attribute, just like in Saurabh Chandra Patel's answer, who now should be the accepted answer! If you can detect IE/Edge efficiently, a tip is to use srcdoc-polyfill library only for them and the "pure" srcdoc attribute in all non-IE/Edge browsers (check caniuse.com to be sure).

<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>