Set content of iframe
Asked Answered
D

10

72

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>
Davey answered 23/11, 2011 at 9:48 Comment(7)
Possible duplicate: https://mcmap.net/q/275803/-jquery-add-iframe-with-content/508702Longitude
Duplicate of: https://mcmap.net/q/127878/-creating-an-iframe-with-given-html-dynamically/471696 , which also has a better answer than this one.Oast
Note that HTML5 introduced a new parameter allowing to inject HTML automatically: w3schools.com/tags/att_iframe_srcdoc.asp The only problem is the browser compatibility...Sophistication
@JamesM.Greene is it possible to mark as duplicate if the other question came after this one?Schuck
possible duplicate of putting html inside an iframe (using javascript)Schuck
This answer provides a much cleaner solution IMO: https://mcmap.net/q/275804/-how-to-set-html-content-into-an-iframePrearrange
possible duplicate of set innerHTML of an iframeCathode
D
131

I managed to do it with

var html_string= "content";
document.getElementById('output_iframe1').src = "data:text/html;charset=utf-8," + escape(html_string);
Davey answered 30/11, 2011 at 6:36 Comment(8)
That works great once you make locals and LocalS the same case.Recreation
No, but I never really looked for one.Recreation
@See #10419144Kelm
This method will give you alert boxes with crazy widths. The web page at data:text/html;charset=utf-8,<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{................................................. says: . Your visitors can't read the content of such alert boxes. And they have to use ESC to close the alert box.Lentissimo
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?Soapbox
Relevant answer to manage encoding of data:text/html: #30106976Doublehung
@MitjaGustin injecting a <base> tag into the head of your html might work developer.mozilla.org/en-US/docs/Web/HTML/Element/baseCresida
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!Wrung
L
30

Use the "contents" function:

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

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

Lewse answered 23/11, 2011 at 9:53 Comment(6)
Its not working ,it updating the HTML only ,but there is no BODY tag,how can i fix this ?Davey
The body tag seems to be inserted just fine. See the updated fiddle. jsfiddle.net/fDFca/1Lewse
<iframe id="test"> <html> <head> <title></title> </head> <body> </body> </html> </iframe> ITS FROM UR JSFIDDLE ,inspected through firebug,how its happen ??Davey
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.Lewse
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 escapeDavey
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.Resplendence
A
27

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();
}
Acetyl answered 4/7, 2018 at 6:37 Comment(5)
src="about:blank" not work with safari 10.1 checked at 2018-08-09Salonika
By far the best vanilla JS solution.Hentrich
Your method does works however you just keep replacing the html css not javascript that means any function event is defined it will be defined until you reload the iframe or whole pageSubcortex
This was the only solution that worked for me.Clearheaded
Best solution yet. Even WebFlow uses it too! Thanks!Carrel
C
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

Crust answered 29/9, 2017 at 8:59 Comment(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.Signorelli
this solution fixed the issue I had in Firefox, but it broke Google Chrome, any idea how to make it work in both?Extenuate
S
13

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.

Silverside answered 8/7, 2020 at 21:1 Comment(0)
P
9
$('#myiframe').contents().find('html').html(s); 

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

Pelham answered 23/11, 2011 at 9:52 Comment(0)
S
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);
Sulphonate answered 27/2, 2021 at 6:50 Comment(1)
Works great and probably best answer by far because with this method we can render javascript without duplicating events and functions again and againSubcortex
S
4

Why not use

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

instead of timer ?

Subsolar answered 8/2, 2014 at 18:22 Comment(0)
P
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)

Poulterer answered 23/11, 2011 at 9:53 Comment(0)
F
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://mcmap.net/q/103310/-dynamically-add-script-tag-with-src-that-may-include-document-write

Frustum answered 25/3, 2020 at 20:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.