Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 views
in Technique[技术] by (71.8m points)

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

This doesn't work:

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

Is there a safe browser reliable way to check an iframe if its empty or not?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...