如何处理加载 iframe 时出现的错误? [英] How can I handle errors in loading an iframe?
问题描述
我有一个 ,其他网站可以包含它,以便他们的用户可以
POST
将表单返回到我的网站.我想优雅地处理我的站点关闭或我的服务器无法提供 内容(即响应超时或 4xx 或 5xx 错误)的情况.我尝试将
onError
添加到 对象,但这似乎没有任何作用:
I have an <iframe>
that other sites can include so their users can POST
a form back to my site. I'd like to handle gracefully the cases where my site is down or my server can't serve the <iframe>
contents (that is, a response timeout or a 4xx or 5xx error). I tried adding an onError
to the <iframe>
object, but that didn't seem to do anything:
showIFrame = function() {
var iframe = document.createElement('iframe');
iframe.id = 'myIFrame';
iframe.src = 'http://myserver.com/someURLThatFailsToLoad';
iframe.onError = iframe.onerror = myHandler;
document.body.appendChild(iframe);
};
myHandler = function(error) {
document.getElementById('myIFrame').style.display = 'none';
console.error('Error loading iframe contents: ' + error);
return true;
};
如果我的服务器返回 404
,我只会在我的 中获取未找到页面的内容.事实上,该错误处理程序从未被触发.有没有办法让这个工作?
If my server returns a 404
I just get the contents of the not-found page in my <iframe>
. In fact, that error handler isn't ever triggered. Is there a way to make this work?
(我目前正在 Chrome 中进行测试,但我希望它也适用于 FF 和 IE >= 7.)
(I'm currently testing in Chrome, but I'd like it to also work for FF and IE >= 7.)
推荐答案
要检测您的服务器是否已关闭,您可以包含一个来自您自己域的空脚本文件.当服务器关闭时,onerror
事件处理程序将触发:
To detect whether your server is down or not, you can include an empty script file from your own domain. When the server is down, the onerror
event handler will fire:
var el = document.createElement('script');
el.onerror = errorFunction;
el.src = "somebogusscript.js?" + new Date().getTime();
document.body.appendChild(el);
注意:不要忘记在 src
属性中添加一个随机字符串,以避免客户端使用缓存版本(这可能会停止查看服务器).
Note: don't forget to add a random string to the src
attribute to avoid the client using a cached version (which could stop a look at the server at all).
这篇关于如何处理加载 iframe 时出现的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!