70

I have the following structure.

<div>
<p>Hello World !!</p>
</div>
<iframe id="myiframe" src='myiframeContent.html'></iframe> 

and I have the following JavaScript variable with content:

var s ="<html><head></head><body><div>Test_Div</div></body></html>";

How can I change the content of iframe with id myiframe with variable s?

I tried:

$("#myiframe").html(s);

Which giving me a very unusual return, it changes all the content of Current page to VAR S Ex : styles,background etc..

How can I set the content of an iframe with a variable that contains HTML?

The content of variable s follows:

 <html>
  <head>
    <title>{page_name}</title>
    <meta name="keywords" content="{page_meta_tags}" />
    <script src="/1.js"></script>
    <script src="/2.js"></script>
 <style>
   h2{
 
 color:red;} 

 h1{
 color:red;}

 body{
     
 background-color:#f0eded;
 color:74f503;
 font-family:Verdana, Geneva, sans-serif;
 background:url({getUrl});}
  </style> 
  </head>
   
  <body>
    yahoo
    <div style="float:right">{pagecomment}</div>
    <div id="blogstart" style="">
      <h1>My Blog</h1>
      {nextPrevPagination}
      {blog} 
      {nextPrevPagination}
    </div>
    <p>My Page Name : {page_name}</p><br/>
    <p>Name of this template</p><br/>
    <p>Date started this page : {page_date}</p><br/>
    <label>Address</label>
    <textarea>{page_address}</textarea>
    
    <span>Country : {page_country} State :{page_state}</span>
    <p>page City : {page_city} Page Pincode {page_pincode}</p>
    <a href="mailto:{page_email}">Email me</a>
    {page_bio_title} and {page_bio_desc}
    <img src="{page_profile}" />
    {page_avatar}
    <p>Contact me : {page_mobile} , {page_landline} </p>
    <a href="http://www.facebook.com/{page_facebook_user}">I am on Facebook</a>
    <a href="http://www.twitter.com/{page_twitter_user}"></a>
  </body>
  
</html>

After applying this variable to the iframe I got like this [inspected through firebug]
Note that it doesn't have BODY ,Head tag, but the above one [var s] has a BODY tag.

<html>  
  
    <title>{page_name}</title>
    <meta content="{page_meta_tags}" name="keywords">
    
    
 <style>
   h2{
 
 color:red;} 

 h1{
 color:red;}

 body{
     
 background-color:#f0eded;
 color:74f503;
 font-family:Verdana, Geneva, sans-serif;
 background:url({url});}
  </style> 
  
    yahoo
    <div style="float: right;">{pagecomment}</div>
    <div style="" id="blogstart">
      <h1>My Blog</h1>
      {nextPrevPagination}
      {blog} 
      {nextPrevPagination}
    </div>
    <p>My Page Name : {page_name}</p><br>
    <p>Name of this template</p><br>
    <p>Date started this page : {page_date}</p><br>
    <label>Address</label>
    <textarea>{page_address}</textarea>
    
    <span>Country : {page_country} State :{page_state}</span>
    <p>page City : {page_city} Page Pincode {page_pincode}</p>
    <a href="mailto:{page_email}">Email me</a>
    {page_bio_title} and {page_bio_desc}
    <img src="{page_profile}">
    {page_avatar}
    <p>Contact me : {page_mobile} , {page_landline} </p>
    <a href="http://www.facebook.com/{page_facebook_user}">I am on Facebook</a>
    <a href="http://www.twitter.com/{page_twitter_user}"></a>
  </html>
Null
  • 1,950
  • 9
  • 30
  • 33
Red
  • 6,230
  • 12
  • 65
  • 112

10 Answers10

130

I managed to do it with

var html_string= "content";
document.getElementById('output_iframe1').src = "data:text/html;charset=utf-8," + escape(html_string);
Red
  • 6,230
  • 12
  • 65
  • 112
  • 2
    That works great once you make locals and LocalS the same case. – Lawson May 07 '13 at 19:18
  • 6
    No, but I never really looked for one. – Lawson Nov 09 '13 at 03:59
  • 2
    @See http://stackoverflow.com/questions/10418644/creating-an-iframe-with-given-html-dynamically/10433550#10433550 – mschr Nov 16 '15 at 03:20
  • 4
    This method will give you alert boxes with crazy widths. `The web page at data:text/html;charset=utf-8, {page_name} – Gökhan Mete ERTÜRK Dec 26 '15 at 11:42
  • Is there any way to preserve origin of the document in iframe? If there are any hypertext links in "html_string", then they are resolved localy to main window? – Mitja Gustin Sep 16 '16 at 11:41
  • Relevant answer to manage encoding of `data:text/html`: https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings – vmarquet May 04 '18 at 10:31
  • @MitjaGustin injecting a `` tag into the head of your html might work https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base – EoghanM Sep 02 '19 at 12:50
  • There is something like zillion posts around showing something similar but using encodeURI instead of escape, and that is just plain WRONG. This is the only solution working when you inject a body with background color for some reason on chrome at least. THANKS A LOT! – Goran.it Mar 09 '20 at 03:57
31

Use the "contents" function:

$('#some-id').contents().find('html').html("some-html")

Relevant fiddle: http://jsfiddle.net/fDFca/

x10
  • 3,820
  • 1
  • 24
  • 32
  • 1
    Its not working ,it updating the HTML only ,but there is no BODY tag,how can i fix this ? – Red Nov 23 '11 at 11:26
  • 1
    The body tag seems to be inserted just fine. See the updated fiddle. http://jsfiddle.net/fDFca/1/ – x10 Nov 23 '11 at 12:13
  • 1
    `` ITS FROM UR JSFIDDLE ,inspected through firebug,how its happen ?? – Red Nov 23 '11 at 12:35
  • 4
    Please don't shout at me. It's the way Firefox/Firebug/whatever displays stuff on a page. Try it with Chrome and you'll see it shows the Body tag just fine. – x10 Nov 23 '11 at 13:06
  • ahhh no brother...its not shouting ,but my English is very poor,and it makes me dirty.its ok i managed it with `SRC`,passing data to the `SRC` with `escape` – Red Nov 23 '11 at 14:32
  • 3
    Note if your iframes are generated from the JS rather than static, you'll want to set the src...src='javascript:void(0)' Otherwise, it will write in your content, then attempt to load the src (even if there isn't any) and leave you with a blank iframe. – sbuck Feb 19 '13 at 11:07
26

Unified Solution:

In order to work on all modern browsers, you will need two steps:

  1. Add javascript:void(0); as src attribute for the iframe element. Otherwise the content will be overriden by the empty src on Firefox.

    <iframe src="javascript:void(0);"></iframe>
    
  2. Programatically change the content of the inner html element.

    $(iframeSelector).contents().find('html').html(htmlContent);
    

Credits:

Step 1 from comment (link) by @susan

Step 2 from solutions (link1, link2) by @erimerturk and @x10

Gavin
  • 4,458
  • 3
  • 24
  • 37
  • 2
    just tried this, in IE11 the "javascript:void(0);" value resulted in a DNS error page being displayed in the initial iframe. I replaced it with "about:blank" and it worked. – Cee McSharpface Nov 29 '18 at 20:25
  • this solution fixed the issue I had in Firefox, but it broke Google Chrome, any idea how to make it work in both? – Federico Resnizky Aug 02 '22 at 13:24
24

I needed to reuse the same iframe and replace the content each time. I've tried a few ways and this worked for me:

// Set the iframe's src to about:blank so that it conforms to the same-origin policy 
iframeElement.src = "about:blank";

// Set the iframe's new HTML
iframeElement.contentWindow.document.open();
iframeElement.contentWindow.document.write(newHTML);
iframeElement.contentWindow.document.close();

Here it is as a function:

function replaceIframeContent(iframeElement, newHTML)
{
    iframeElement.src = "about:blank";
    iframeElement.contentWindow.document.open();
    iframeElement.contentWindow.document.write(newHTML);
    iframeElement.contentWindow.document.close();
}
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
mrrrk
  • 2,186
  • 20
  • 17
12

You want to be using the iframe's srcdoc attribute for that (MDN documentation).

var html_string = "<html><body><h1>My epic iframe</p></body></html>";
document.querySelector('iframe').srcdoc = html_string;

The nice thing about using this method over for example Red's method listed on this page, is that iframe contents added with srcdoc are seen as the same-origin. That way can continue to manipulate and access the iframe with JavaScript if you wish.

Juice10
  • 221
  • 3
  • 10
9
$('#myiframe').contents().find('html').html(s); 

you can check from here http://jsfiddle.net/Y9beh/

erimerturk
  • 4,230
  • 25
  • 25
6

Using Blob:

var s ="<html><head></head><body><div>Test_Div</div></body></html>";
var iframe = document.getElementById("myiframe");
var blob = new Blob([s], {type: "text/html; charset=utf-8"});
iframe.src = URL.createObjectURL(blob);
Vikas Kandari
  • 1,612
  • 18
  • 23
Pēteris Caune
  • 43,578
  • 6
  • 59
  • 81
  • Works great and probably best answer by far because with this method we can render javascript without duplicating events and functions again and again – Vikas Kandari Jun 01 '21 at 19:28
4

Why not use

$iframe.load(function () {
    var $body = $('body', $iframe.get(0).contentWindow.document);
    $body.html(contentDiv);
});

instead of timer ?

Serg
  • 6,742
  • 4
  • 36
  • 54
2

You need -

var $frame = $('myiframe');
    setTimeout( function() {
            var doc = $frame[0].contentWindow.document;
            var $body = $('body',doc);
            $body.html('<div>Test_Div</div>');
    }, 1 );

Code taken from - putting html inside an iframe (using javascript)

Community
  • 1
  • 1
ipr101
  • 24,096
  • 8
  • 59
  • 61
0

If you want to set an html content containg script tag to iframe, you have access to the iframe you created with:

$(iframeElement).contentWindow.document

so you can set innerHTML of any element in this.

But, for script tag, you should create and append an script tag, like this:

https://stackoverflow.com/a/13122011/4718434

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
yaya
  • 7,675
  • 1
  • 39
  • 38