views:

1603

answers:

3

Is there anyway to unload a page that has been loaded inside of an iframe? I do not want to have to change the iframe src to a blank page if possible. I am basically looking for something that will do something like this $('#frameID').attr("src",""); except that code does not seem to clear the previously loaded page.

Is there a "unload" function that I can call which will reset the iframe so that it does not have any content loaded inside?

+1  A: 

$('#frameID').contentWindow.document.body.innerHTML = '';

As with any iframe, this only works if you're on the same domain.

Steve Brewer
can you do `.contentWindow`?
geowa4
A: 

First, get the document of the frame:

var frame = $('#frameId').get(0);
var frameDoc = frame.contentDocument || frame.contentWindow.document;

Then, blank it:

frameDoc.getElementsByTagName('body')[0].innerHTML = "";

I think this should work too:

$('body', frameDoc).html("");

Now, you might want to do something with any scripts that might be loaded in the head, but this should get you started.

geowa4
+2  A: 

The other solutions use innerHTML, which won't always work in XHTML. They also only clear document.body (anything in the <head> is still present). Here is a solution that uses the DOM:

var frame = document.getElementById("myFrame"),
frameDoc = frame.contentDocument || frame.contentWindow.document;
frameDoc.documentElement.parentNode.removeChild(frameDoc.documentElement);

This solution uses innerHTML:

var frame = document.getElementById("myFrame"),
frameDoc = frame.contentDocument || frame.contentWindow.document;
frameDoc.documentElement.innerHTML = "";
Eli Grey
thanks I ended up using this
Dan