How to clear the content of an IFRAME?

2019-02-02 22:19发布

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.

10条回答
做自己的国王
2楼-- · 2019-02-02 22:38

Or you can do this :

var iframe_element = window.frames['iframe_name'];
iframe_element.document.open();
iframe_element.document.close();
查看更多
Animai°情兽
3楼-- · 2019-02-02 22:45
function getContentFromIframe(iFrameName)
{
    var myIFrame = document.getElementById(iFrameName);
    var content = myIFrame.contentWindow.document.body.innerHTML;

    //Do whatever you need with the content    
}
查看更多
一纸荒年 Trace。
4楼-- · 2019-02-02 22:46

// First I get the window from its Id.

var my_content = document.getElementById('my_iframe').contentWindow.document;

// Then I clear it by setting the body tag inner HTML to an empty string.

my_content.body.innerHTML="";

// Now when I write my new content it does not get appended to the end of the body and the iframe body will contain only fresh content.

my_content.write(new_content);
查看更多
叼着烟拽天下
5楼-- · 2019-02-02 22:52

Just get the Iframe and remove the documentElement from it. The Iframe will be blank

 var frame = document.getElementById("YourFrameId"),
 frameDoc = frame.contentDocument || frame.contentWindow.document;
 frameDoc.removeChild(frameDoc.documentElement);
查看更多
干净又极端
6楼-- · 2019-02-02 22:55

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).

查看更多
Summer. ? 凉城
7楼-- · 2019-02-02 22:55

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);

查看更多
登录 后发表回答