如何在JavaScript中检测Internet连接是否离线?


当前回答

IE 8将支持window.navigator.onLine属性。

但当然,这对其他浏览器或操作系统没有帮助。考虑到了解Ajax应用程序中的在线/离线状态的重要性,我预计其他浏览器供应商也将决定提供该属性。

在此之前,XHR或Image()或<img>请求都可以提供接近您想要的功能。

更新(2014/11/16)

大多数浏览器现在都支持这个属性,但结果会有所不同。

引用自Mozilla文档:

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking. In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. All other conditions return a true value.

其他回答

您可以通过发出失败的XHR请求来确定连接已丢失。

标准的方法是重试请求几次。如果没有通过,请提醒用户检查连接,然后优雅地失败。

旁注:将整个应用程序置于“脱机”状态可能会导致大量易出错的处理状态工作。无线连接可能来来去去,等等。因此,最好的办法可能是优雅地失败,保存数据,并提醒用户。允许他们最终解决连接问题(如果有的话),并在一定程度上原谅他们继续使用你的应用。

旁注:您可以检查像谷歌这样的可靠站点的连接性,但这可能并不完全有用,因为只是尝试发出自己的请求,因为虽然谷歌可能可用,但您自己的应用程序可能不可用,并且您仍然必须处理自己的连接问题。尝试向谷歌发送ping信息是确认网络连接本身已中断的好方法,因此如果该信息对您有用,那么可能值得费心。

Sidenote: Sending a Ping could be achieved in the same way that you would make any kind of two-way ajax request, but sending a ping to google, in this case, would pose some challenges. First, we'd have the same cross-domain issues that are typically encountered in making Ajax communications. One option is to set up a server-side proxy, wherein we actually ping google (or whatever site), and return the results of the ping to the app. This is a catch-22 because if the internet connection is actually the problem, we won't be able to get to the server, and if the connection problem is only on our own domain, we won't be able to tell the difference. Other cross-domain techniques could be tried, for example, embedding an iframe in your page which points to google.com, and then polling the iframe for success/failure (examine the contents, etc). Embedding an image may not really tell us anything, because we need a useful response from the communication mechanism in order to draw a good conclusion about what's going on. So again, determining the state of the internet connection as a whole may be more trouble than it's worth. You'll have to weight these options out for your specific app.

如何发送一个不透明的http请求到google.com与无cors?

    fetch('https://google.com', {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'no-cors',
    }).then((result) => {
        console.log(result)
    }).catch(e => {
        console.error(e)
    })

设置no-cors的原因是,即使在我的pc上取消网络连接时,我也收到了cors错误。所以不管有没有网络连接,我都被封锁了。添加no-cors使请求不透明,这显然似乎绕过cors,并允许我只是简单地检查我是否可以连接到谷歌。

供参考:我在这里使用fetch进行http请求。 https://www.npmjs.com/package/fetch

有很多方法可以做到这一点:

AJAX请求到您自己的网站。如果请求失败,很有可能是连接有问题。JQuery文档中有关于处理失败AJAX请求的章节。这样做时要注意同源策略,这可能会阻止您访问域外的网站。 你可以在img中添加一个onerror,比如<img src="http://www.example.com/singlepixel.gif" onerror="alert('Connection dead');"/ >。

如果源图像被移动/重命名,此方法也可能失败,并且通常是一个不如ajax选项的选择。

因此,有几种不同的方法来尝试和检测这种情况,没有一种是完美的,但在没有跳出浏览器沙箱并直接访问用户的网络连接状态的能力的情况下,它们似乎是最好的选择。

请求头错误

$.ajax({
    url: /your_url,
    type: "POST or GET",
    data: your_data,
    success: function(result){
      //do stuff
    },
    error: function(xhr, status, error) {

      //detect if user is online and avoid the use of async
        $.ajax({
            type: "HEAD",
            url: document.location.pathname,
            error: function() { 
              //user is offline, do stuff
              console.log("you are offline"); 
              }
         });
    }   
});

我认为这是一个非常简单的方法。

var x = confirm("Are you sure you want to submit?");
if (x) {
  if (navigator.onLine == true) {
    return true;
  }
  alert('Internet connection is lost');
  return false;
}
return false;