JavaScript: How to detect that the Internet Connection is foffline

There are a number of ways to do this:

  • AJAX request to your own website. If that request fails, there's a good chance it's the connection at fault. The JQuerydocumentation has a section on handling failed AJAX requests. Beware of the Same Origin Policy when doing this, which may stop you from accessing sites outside your domain.
  • You could put an onerror in an img, like

    <img src='http://www.example.com/singlepixel.gif' 
         
    onerror='alert("Connection dead");' />

    This method could also fail if the source image is moved / renamed, and would generally be an inferior choice to the ajax option.

So there are several different ways to try and detect this, none perfect, but in the absence of the ability to jump out of the browser sandbox and access the user's net connection status directly, they seem to be the best options.

 

 

IE 8 will support the window.navigator.onLine property.

network: function() {
   
var state = navigator.onLine ? "online" : "offline";
   
return state;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值