Set content of iframe

JavascriptJqueryHtmlIframe

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

I managed to do it with

var html_string= "content";
document.getElementById('output_iframe1').src = "data:text/html;charset=utf-8," + escape(html_string);

Solution 2 - Javascript

Use the "contents" function:

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

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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);
iframeElementcontentWindow.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();
}

Solution 5 - Javascript

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.

Solution 6 - Javascript

$('#myiframe').contents().find('html').html(s); 

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

Solution 7 - Javascript

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);

Solution 8 - Javascript

Why not use

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

instead of timer ?

Solution 9 - Javascript

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 - https://stackoverflow.com/questions/620881/putting-html-inside-an-iframe-using-javascript

Solution 10 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRedView Question on Stackoverflow
Solution 1 - JavascriptRedView Answer on Stackoverflow
Solution 2 - Javascriptx10View Answer on Stackoverflow
Solution 3 - JavascriptGavinView Answer on Stackoverflow
Solution 4 - JavascriptmrrrkView Answer on Stackoverflow
Solution 5 - JavascriptJuice10View Answer on Stackoverflow
Solution 6 - JavascripterimerturkView Answer on Stackoverflow
Solution 7 - JavascriptPēteris CauneView Answer on Stackoverflow
Solution 8 - JavascriptSergeiView Answer on Stackoverflow
Solution 9 - Javascriptipr101View Answer on Stackoverflow
Solution 10 - JavascriptyayaView Answer on Stackoverflow