Let’s say you want to generate dynamically iframe and instead of point to external source:

<script>
var iframe = document.createElement('iframe'),
    body = document.body || document.getElementsByTagName("body")[0];

iframe.src = "myiframecontent.html";
if (body) {
    body.appendChild(iframe);
}
</script>

you want to create dynamically content inside iframe. Sounds crazy, but… it’s possible. Partially. We can use data URI with content encoded using base64. By the way, you can use base64 encoding/decoding online tool, to encode your content to base64 format.

Let’s say we want to generate iframe with following HTML code inside iframe:

Iframe content

It can looks like this example:

<script>
var iframe = document.createElement('iframe'),
    body = document.body || document.getElementsByTagName("body")[0];
        iframe.src = 'data:text/html;base64,PCFET0NUWVBFIGh0bWw+PGh0bWw+PGhlYWQ+PHRpdGxlPklmcmFtZSBjb250ZW50PC90aXRsZT48bWV0YSBjaGFyc2V0PSJVVEYtOCIvPjwvc3R5bGU+PC9oZWFkPjxib2R5PjwvYm9keT48L2h0bWw+';
if (body) {
    body.appendChild(iframe);
}
</script>

Try example how it works.

Now, here are the results in following browsers:

  • Internet Explorer 11 / Windows 8.1 – it doesn’t work and it’s even expected per explanation in MSDN documentation which says:

    Data URIs are supported only for the following elements and/or attributes: object (images only), img, input type=image, link, CSS declarations that accept a URL, such as background, backgroundImage, and so on. Data URIs can be nested.

    Screenshot from console what is generated: iframe_code_ie11

  • Google Chrome 33.0.1750.154 m / Windows 7 – it doesn’t work and Chrome trying to download content instead of rendering. See: iframe_chrome_33
  • Firefox 28 / Windows 7 – rendering as expected. See results from console: iframe_code
  • Opera 20.0.1387.82 / Windows 7 – rendering as expected.

So, not all specified browsers are ready to use data URI to create content inside iframe.

Comments

You can leave a response, or trackback from your own site.

2 Responses to “Generate dynamically iframe and it’s content”

  1. Enrico, 2 January 2015

    If you have to encode html that contains a private text or code, you can use Base64 Encoder which is a client-side encoder and it doesn’t send the data to the server

  2. Cezary Tomczyk, 6 January 2015

    For sensitive data you might consider to use bcryptjs.

Before you add comment see for rules.

Leave a Reply

Your email address will not be published. Required fields are marked *

3p5d6o