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


当前回答

对于两种不同的情况,有两个答案:-

If you are using JavaScript on a website(i.e; or any front-end part) The simplest way to do it is: <h2>The Navigator Object</h2> <p>The onLine property returns true if the browser is online:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "navigator.onLine is " + navigator.onLine; </script> But if you're using js on server side(i.e; node etc.), You can determine that the connection is lost by making failed XHR requests. The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.

其他回答

window.navigator.onLine

是你要找的,但这里要添加的东西很少,首先,如果它是你想要持续检查的应用程序上的一些东西(比如看看用户是否突然脱机,在这种情况下大多数时候是正确的,那么你也需要监听变化),为此你添加事件监听器到窗口来检测任何变化,为了检查用户是否脱机,你可以这样做:

window.addEventListener("offline", 
  ()=> console.log("No Internet")
);

检查是否在线:

window.addEventListener("online", 
  ()=> console.log("Connected Internet")
);
 if(navigator.onLine){
  alert('online');
 } else {
  alert('offline');
 }

您可以通过发出失败的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.

您可以使用$.ajax()的错误回调,它在请求失败时触发。如果textStatus等于字符串"timeout",这可能意味着连接中断:

function (XMLHttpRequest, textStatus, errorThrown) {
  // typically only one of textStatus or errorThrown 
  // will have info
  this; // the options for this ajax request
}

医生说:

错误:一个函数被调用,如果请求 失败。函数被传递了3个 参数:XMLHttpRequest对象 描述错误类型的字符串 这是可选的 异常对象,如果发生。 第二个可能的值 参数(除null外)为"timeout", "error", "notmodified"和 “parsererror”。这是一个Ajax事件

例如:

 $.ajax({
   type: "GET",
   url: "keepalive.php",
   success: function(msg){
     alert("Connection active!")
   },
   error: function(XMLHttpRequest, textStatus, errorThrown) {
       if(textStatus == 'timeout') {
           alert('Connection seems dead!');
       }
   }
 });

正如olliej所说,使用导航器。在线浏览器属性比发送网络请求更可取,因此developer.mozilla.org/En/Online_and_offline_events甚至被旧版本的Firefox和IE支持。

最近,WHATWG已经指定了在线和离线事件的添加,以防您需要在导航器上进行反应。在线更改。

请注意Daniel Silveira发布的链接,他指出依赖这些信号/属性与服务器同步并不总是一个好主意。