Robbert
Robbert

Reputation: 6582

Replacing HTML source of an iframe document

I am working on a page that will display the contents of a database field. The contents are in HTML format and includes an entire webpage

<html>
  <title>Some title</title>
  <style type="text/css">
     /* CSS content here */
  </style>
  <body>
    <!-- body content here -->
  </body>
</html>

I need to display all of this inside another webpage so I thought using an iframe would allow me to negate any css from the parent page. However, I cannot figure out how to overwrite the contents of the iframe document.

What I've done so far is retrieve the data and then use the following

$("#iframe_constainer")
  .find('iframe:first').contents().find('html:first').html(myHTML);

My web page includes a div called iframe_container which contains an iframe.

<div id="iframe_container"><iframe/></div>

This is working okay, but the contents of myHTML are getting wrapped inside html tags. So the effect is like this

<html>
  <html>
    <title>Some title</title>
    <style type="text/css">
       /* CSS content here */
    </style>
    <body>
      <!-- body content here -->
    </body>
  </html>
</html>

I know it's because I'm finding the html tag in the iframe and changing the HTML. Is there a way to overwrite the entire document using jQuery?

Upvotes: 0

Views: 3172

Answers (2)

Mike Carpenter
Mike Carpenter

Reputation: 410

Opening the document and closing afterwards will fix the issue with appending the content

var iframe = document.getElementById('iframeID');
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(htmlData);
iframe.contentWindow.document.close();

Upvotes: 2

suff trek
suff trek

Reputation: 39777

You don't really need jQuery for this, just use document.write to write content to the iframe to completely replace iframe's document.

E.g. (in plain vanilla JS)

document.getElementById("myIframeId").contentWindow.document.write(myHTML);

Upvotes: 0

Related Questions