[英]Error handling iframe with js
I'm using $("#element").attr("src", "http://url.com/page");
我正在使用
$("#element").attr("src", "http://url.com/page");
to set several iframes. 设置几个iframe
Is there a way to determine if an HTTP error occurred while setting a specific iframe and handle it accordingly? 有没有一种方法可以确定在设置特定的iframe时是否发生HTTP错误并相应地进行处理?
The onerror
event of the <iframe>
does not work anymore, unfortunately. 不幸的是,
<iframe>
的onerror
事件不再起作用。
Still, you could use a workaround like this : 不过,您可以使用类似的解决方法:
Bind a load
event to all of the iframes you are loading 将
load
事件绑定到要load
所有iframe
Throw a setTimeout
with arbitrary time for each <iframe>
, like 60000 (1mn) or less in the mean time 为每个
<iframe>
抛出一个具有任意时间的setTimeout
,平均时间小于等于60000(1mn)
If the load event triggers, clear the setTimeout
. 如果加载事件触发,则清除
setTimeout
。
It's not complete error handling, more a workaround. 它不是完整的错误处理,而是一种解决方法。 I used to do it with
JSONP
requests as there is no error handling too. 我以前使用
JSONP
请求来执行此操作,因为也没有错误处理。
var timeout;
$("#iframe").attr("src", "url-cross-domain.html").on("load", function() {
clearTimeout(timeout);
console.log("loaded !");
}):
timeout = setTimeout(function() {
$("#iframe").off("load").remove();
console.error("iframe loading failed");
}, 60000);
It has several limitations, for example you'll be unable to get the request response code. 它有几个限制,例如,您将无法获得请求响应代码。 But it worth a try.
但是值得一试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.