how to hide an iframe if content is empty

2019-07-27 02:13发布

问题:

I am using iframe in which I am displaying some content from external url. I want to hide the iframe if there is no content to display (i.e empty). please let me know how to do this.

回答1:

If you want to check content from external url inside iframe is empty, 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. Well if you can use jQuery, check it's length property. This is cross-browser compatible. If it's zero, it doesn't exist.

CODE:

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.

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



回答2:

Use Jquery .content() to evaluate the content of the iframe and .hide() to hide it. If you want to show it again latter use .toggle() instead.



回答3:

No.

This cannot be done by a script on the calling page. The calling page will not be able to access the external document object loaded inside the iframe due to cross-domain security restriction.