如何处理加载iframe时的错误? [英] How can I handle errors in loading an iframe?

查看:164
本文介绍了如何处理加载iframe时的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个< iframe> 其他网站可以包含,所以他们的用户可以将 POST 我的网站我想妥善地处理我的网站关闭的情况,或者我的服务器无法提供< iframe> 内容(即响应超时或4xx或5xx错误)。我尝试将 onError 添加到< iframe> 对象中,但似乎没有做任何事情: / p>

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 < iframe> 中获取未找到页面的内容。实际上,该错误处理程序不会被触发。有没有办法使这项工作?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆