Here are a few ways to determine whether or not to connect
The first gets the network settings, traverses the properties, checks whether the IPV4 has an IP address
1 //Determine network status2 static Judgingaddrinfo () {3 varInterfaces = require (' OS '). Networkinterfaces ();4 for(varIinchinterfaces) {5 varIfobj =Interfaces[i];6 for(varn = 0; n < ifobj.length; n++) {7 if(ifobj[n].family = = ' IPv4 ' && ifobj[n].address! = ' 127.0.0.1 ') {8 return true;9 }Ten } One } A return false; -}
The second method: var online = navigator.online; Chrome. Returns the browser's networking status. Normal networking (在线)返回true,不正常联网(离线)返回 false。 once the browser's networking status changes, the property value changes.
However, these two methods are less accurate in some cases, and checking to the networked state does not mean that the browser will be able to connect to the Internet. There are other reasons why you might be mistaken, such as if your computer has a virtualization software installed and there may be a virtual network card that will always show the normal network. Therefore, if you want to get the exact internet status of your browser, you should use additional checking methods.
The third method:
By initiating a network resource request, if the request succeeds, the network connection is fine, but this method relies on the requested resource!
1 //by initiating a request2Require ("Request")3. Get (' http://www.baidu.com ')4. On (' response ',function(response) {5Console.log (Response.statuscode)// $6 })7 8 or9 //by requesting resourcesTen vari = ); OneI.onload =function () { AConsole.log ("Load") -CallBack (true); - }; theI.onerror =function () { -Console.log ("Err") -CallBack (false); - }; +I.SRC = ' https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png?id= ' + date.now ( );
Determine if your computer is connected to a network