How to check if iframe is empty/null/undefined?

前端 未结 2 831
猫巷女王i
猫巷女王i 2020-12-20 23:21

This doesn\'t work:

if(document.getElementById(\"iframe\").innerHTML==\'\'){

Is there a safe browser reliable way to check an iframe if its

相关标签:
2条回答
  • 2020-12-21 00:10

    Check the frame's contentDocument property. IE 7 and earlier support the contentWindow property instead, but there is a simple cross browser example at http://www.w3schools.com/jsref/prop_frame_contentdocument.asp.

    A less-reliable method but might be what you want... check the src property.

    You can read about other frame properties at http://www.w3schools.com/jsref/dom_obj_frame.asp

    0 讨论(0)
  • 2020-12-21 00:11

    Well if you can use jQuery, check it's length property. This is cross-browser compatible. If it's zero, it doesn't exist. Something like this:

    if(!$("#iframeid").length) {
        // iframe doesn't exist
    }
    

    EDIT:

    After seeing your comments on your question:

    If you want to check if no page loaded inside iframe, and the iframe is not cross-domain you could check for the existence of the body tag inside of the iframe. If it exists, then something loaded.

    Something like this:

    if($("#iframeid").contents().find("body").length) {
        // some html page loaded in iframe
    }
    

    If the iframe is cross-domain, you will be blocked by the same-origin policy. Otherwise this will work.

    0 讨论(0)
提交回复
热议问题