views:

1036

answers:

4

How do I clear the content of my IFRAME element, using javascript, without loading a blank page into it?

I can figure out to do this: iframe_element.src = "blank.html", but there must be a better, instant, method.

+12  A: 
about:blank

is a "URL" that is blank. It's always clear

You can set the page's source to that, and it will clear.

McKay
can you give me example.. how can i do it?..
Sikender
iframe_element.src = "about:blank"
victor hugo
+1  A: 

I have had difficulties with "about:blank" on pages with many IFrames. It does not seem to be a valid location in every browser (I never found out for sure, though). Anyway, I am happy with javascript:void(0);

Pekka
what happens if Javascript is disabled?
AnthonyWJones
He is specifically asking how to reset a IFrame location after Javascript. While I imagine that javascript: urls gracefully downgrade, I don't know for sure.
Pekka
+2  A: 

Your technique is the most robust. Its the one I use myself. At times content may be delivered over HTTPS and the use of about:blank can cause warning messages to appear to the effect of "do you want to include content from unsecure location" or some such thing.

Something being instant is a matter of perception however if you have a single Blank.html file on your site configured with a long cache expiry the client will only ever fetch the page once (at the most once per-session).

AnthonyWJones
+1  A: 

You could also do this:

<html>
<head>
<script>
    var doc = null;
    window.onload = function() {
        alert("Filling IFrame");
        doc = document.getElementById("test");

        if( doc.document ) {
            document.test.document.body.innerHTML = "<h1>test</h1>"; //Chrome, IE
        }else {
            doc.contentDocument.body.innerHTML = "<h1>test</h1>"; //FireFox
        }

            setTimeout(function() { 
                alert("Clearing IFrame");

                if( doc.document ) {
                    document.test.document.body.innerHTML = ""; //Chrome, IE
                }else {
                    doc.contentDocument.body.innerHTML = ""; //FireFox
                }

            }, 1000);
        };
    </script>
</head>

<body>
    <iframe id="test" name="test">

    </iframe>
</body>
</html>
Jared