'Replace Entire Content of Iframe

Is there a way to replace the ENTIRE contents of an iframe using Javascript (or Jquery)?

For example if my iframe had the following content...

blah outside of html
<html>
<head>
</head>
<body>
<h1> my title </h1>
</body>
</html>
blah outside of html

..It could all be replaced by your script :)

The best that I've seen so far is this:

$(youriframe).contents().find('html').html('your content here'); 

but that still wouldn't replace the content outside of the html tags. We have an interesting scenario where we must assure that ALL the content is replaced.

OR a new iframe with fresh content is created and simply replaces the previous iframe.

Please no comments about the src attribute.



Solution 1:[1]

The code works fine in Chrome or FireFox, but in IE8, nothing will be showed or the scroll bar in iframe won't appear.

Tried this one:

var doc = document.getElementById(iframeId).contentWindow.document;
doc.open();
doc.write(iframeContent);
doc.close();

this works on my case, both ie8 and FF/chrome.

If i use Rachel's method, the iframe content will be like this in all browsers:

<iframe>
    <html>
        <head>
        </head>
        <body>
        </body>
    </html>
</iframe>

Solution 2:[2]

I'm guessing that you're not having problems with cross-site scripting in this instance... Have you had any luck using contentWindow? Something like this seems to work well enough for me:

iframe = document.getElementById('iframe_id');
iframe.contentWindow.document.open()
iframe.contentWindow.document.write(new_content_here);

Not my idea, found it here: Write elements into a child iframe using Javascript or jQuery

Solution 3:[3]

I solved with this code:

$('#IframeID').contents().find("html").html(html);

Although this way you can work better in many of the cases, there will be more order:

$('#IframeID').contents().find("head").html(head);
$('#IframeID').contents().find("body").html(body);

So, you can play with head and body separately, and a bad change on body will not affect your head.

I tested on Chrome.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 General Grievance
Solution 2 Community
Solution 3 Carlos Eduardo Salazar Mori