javascript 如何检查 iframe 是否为空/空/未定义?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4215952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if iframe is empty/null/undefined?
提问by Alex
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?
是否有安全的浏览器可靠的方法来检查 iframe 是否为空?
Thanks
谢谢
回答by Alex
Well if you can use jQuery, check it's lengthproperty. This is cross-browser compatible. If it's zero, it doesn't exist. Something like this:
好吧,如果您可以使用 jQuery,请检查它的length属性。这是跨浏览器兼容的。如果为零,则不存在。像这样的东西:
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-domainyou could check for the existence of the bodytag inside of the iframe. If it exists, then something loaded.
如果您想检查 iframe 内是否没有加载页面,并且 iframe 不是跨域的,您可以检查bodyiframe 内是否存在标签。如果存在,则加载某些内容。
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.
如果 iframe 是跨域的,您将被同源策略阻止。否则这将起作用。
回答by Brad
Check the frame's contentDocumentproperty. IE 7 and earlier support the contentWindowproperty instead, but there is a simple cross browser example at http://www.w3schools.com/jsref/prop_frame_contentdocument.asp.
检查框架的contentDocument属性。IE 7 及更早版本支持该contentWindow属性,但http://www.w3schools.com/jsref/prop_frame_contentdocument.asp 上有一个简单的跨浏览器示例。
A less-reliable method but might be what you want... check the srcproperty.
一种不太可靠的方法,但可能是您想要的……检查src属性。
You can read about other frame properties at http://www.w3schools.com/jsref/dom_obj_frame.asp
您可以在http://www.w3schools.com/jsref/dom_obj_frame.asp阅读有关其他框架属性的信息

