187

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>   
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
Max
  • 4,152
  • 4
  • 36
  • 52

5 Answers5

229

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>
Heitor
  • 683
  • 2
  • 12
  • 26
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • The problem with the JS approach is that if the HTML contains single quotes (which the OP doesn't know until runtime), they will need to be escaped from a JS point of view in order not to break the innerHTML assignment statement...? – Andrew Swan Apr 24 '13 at 05:19
  • Yes, obviously the JS would need to be valid. This is why, contrary to what I said in my answer, I would almost certainly not do this. I'd just use a normal iframe! – lonesomeday Apr 24 '13 at 08:54
  • 5
    Internet explorer support? Data URI can't represent html files in IE8 – franzlorenzon Apr 24 '13 at 12:05
  • 2
    Is there a way to provide cross origin headers here? Chrome keeps complaining about `Blocked a frame with origin "http://localhost" from accessing a cross-origin frame`. – jozxyqk Jan 03 '14 at 10:06
  • 1
    @AndrewSwan I don't quite understand the problem with the single quotes. Can you give me an example? – Septagram May 27 '15 at 09:31
  • 5
    For anyone like me who was looking how to encode HTML this way with php, you want rawurlencode (http://php.net/manual/en/function.rawurlencode.php) – Braiba Dec 02 '15 at 13:27
  • well you could try backticks in the script, it really helped me out a lot with escapes and stuff. – My1 Nov 28 '16 at 12:17
  • 4
    Note that if you use `innerHTML` browser will not execute descendant script tags. For more information check [Security considerations section](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) of Element.innerHTML MDN page. – Leonid Vasilev Feb 09 '17 at 06:49
  • @lonesomeday How you have encoded html to "%3Chtml%3E%3Cbody%3Efoo%3C/body%3E%3C/html%3E" by using jquery.parseHTML() or any vanilla javascript? – rselvaganesh Apr 01 '17 at 09:11
  • 1
    @rselvaganesh `"data:text/html;charset=utf-8," + encodeURI(html)` – lonesomeday Apr 01 '17 at 09:14
  • why down not work? https://jsfiddle.net/g57kync0/ – tumbudu May 12 '20 at 11:48
  • @tumbudu Give it a whirl with `encodeURIComponent`, or give the better solution in my answer a go. – lonesomeday May 12 '20 at 12:11
153

use html5's new attribute srcdoc (srcdoc-polyfill) Docs

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

Browser support - Tested in the following browsers:

Microsoft Internet Explorer
6, 7, 8, 9, 10, 11
Microsoft Edge
13, 14
Safari
4, 5.0, 5.1 ,6, 6.2, 7.1, 8, 9.1, 10
Google Chrome
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24.0.1312.5 (beta), 25.0.1364.5 (dev), 55
Opera
11.1, 11.5, 11.6, 12.10, 12.11 (beta) , 42
Mozilla FireFox
3.0, 3.6, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 (beta), 50

If your HTML contains double quotes, consider escaping its double quotes

<iframe 
    srcdoc="<html>
              <body>&quot;Hello&quot;</body>
           </html>">
</iframe>

...or use Javascript to set the srcdoc attribute dynamically

iframe.srcdoc = '<html>
                  <body>"Hello"</body>
               </html>';

Remember wait for the iframe's onload event before trying to use Javascript to manipulate the iframe's content (before adding event listeners, etc)

Nate Anderson
  • 18,334
  • 18
  • 100
  • 135
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
24

According to W3Schools, HTML 5 lets you do this using a new "srcdoc" attribute, but the browser support seems very limited.

Andrew Swan
  • 13,427
  • 22
  • 69
  • 98
  • 5
    There is also [a Polyfill for srcdoc](https://github.com/jugglinmike/srcdoc-polyfill). – Uwe Keim Sep 02 '14 at 05:41
  • 2
    @UweKeim Thanks for suggesting the polyfill. It's lightweight and works great. – The Muffin Man Oct 16 '14 at 04:16
  • 1
    According to [caniuse.com](https://caniuse.com/#feat=iframe-srcdoc) only infamous Microsoft's IE and Edge browsers (besides Opera Mini) don't support the **srcdoc** attribute, so it is NOT "very limited". Just use [srcdoc-polyfill](https://github.com/jugglinmike/srcdoc-polyfill) for Microsoft users. – Heitor Dec 26 '17 at 04:36
4

iframe srcdoc: This attribute contains HTML content, which will override src attribute. If a browser does not support the srcdoc attribute, it will fall back to the URL in the src attribute.

Let's understand it with an example

<iframe 
    name="my_iframe" 
    srcdoc="<h1 style='text-align:center; color:#9600fa'>Welcome to iframes</h1>"
    src="https://www.birthdaycalculatorbydate.com/"
    width="500px"
    height="200px"
></iframe>

Original content is taken from iframes.

Naruto
  • 103
  • 1
  • 9
4

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.

An object with a unencoded dataUri might have also fit your need if it was only to load a portion of data text:

The HTML <object> element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin.

https://codepen.io/gc-nomade/pen/bGKQVRr or snippet below

body {display:flex;min-height:25em;}
p {margin:auto;}
object {margin:0 auto;background:lightgray;}
<p>here My uploaded content: </p>
<object data='data:text/html,
  <style>

.table {
  display: table;
  text-align:center;
  width:100%;
  height:100%;
}

.table > * {
  display: table-row;
}

.table > main {
  display: table-cell;
  height: 100%;
  vertical-align: middle;
}
</style>


<div class="table">
  <header>
    <h1>Title</h1>
    <p>subTitle</p>
  </header>

  <main>
    <p>Collection</p>
    <p>Version</p>
    <p>Id</p>
  </main>

  <footer>
    <p>Edition</p>
  </footer>'>

</object>

But keeping your Iframe idea, You could also load your HTML inside your iframe tag and set it as the srcdoc value.You should not have to mind about quotes nor turning it into a dataUri but only mind to fire onload once.

The HTML Inline Frame element (<iframe>) represents a nested browsing context, embedding another HTML page into the current one.

Both iframe below will render the same, one require extra javascript.

example loading a full document : https://codepen.io/gc-nomade/pen/JjZeYyg or snippet below

body {
  display: flex;
  min-height: 25em;
}

p {
  margin: auto;
}

iframe {
  margin: 0 auto;
  min-height: 100%;
  background:lightgray;
}
<p>here my uploaded contents =>:</p>
  <iframe srcdoc='<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <style>
html, body {
  height: 100%;
  margin:0;
}

body.table {
  display: table;
  text-align:center;
  width:100%;
}

.table > * {
  display: table-row;
}

.table > main {
  display: table-cell;
  height: 100%;
  vertical-align: middle;
}
</style>
</head>

<body class="table">
  <header>
    <h1>title</h1>
    <p>injected via <code>srcdoc</code></p>
  </header>

  <main>
    <p>Collection</p>
    <p>Version</p>
    <p>Id</p>
  </main>

  <footer>
    <p>Edition</p>
  </footer>
</body>
</html>'>

</iframe>

  <iframe onload="this.setAttribute('srcdoc', this.innerHTML);this.setAttribute('onload','')">
    <!-- below html loaded -->
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>
      <title>Test</title>
      <style>
        html,
        body {
          height: 100%;
          margin: 0;
          overflow:auto;
        }
        
        body.table {
          display: table;
          text-align: center;
          width: 100%;
        }
        
        .table>* {
          display: table-row;
        }
        
        .table>main {
          display: table-cell;
          height: 100%;
          vertical-align: middle;
        }
      </style>
    </head>

    <body class="table">
      <header>
        <h1>Title</h1>
        <p>Injected from <code>innerHTML</code></p>
      </header>

      <main>
        <p>Collection</p>
        <p>Version</p>
        <p>Id</p>
      </main>

      <footer>
        <p>Edition</p>
      </footer>
    </body>

    </html>
    </iframe>
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
  • Could you please show your code example in a codepen? its not working for me, nothing is rendered in the iframe using your 2nd example, thx – OJB1 Dec 02 '22 at 17:25
  • @OJB1 here is the codepen with the iframes : https://codepen.io/gc-nomade/pen/JjZeYyg & the object https://codepen.io/gc-nomade/pen/bGKQVRr – G-Cyrillus Dec 02 '22 at 23:21