简体   繁体   中英

Internet connectivity status by navigator.onLine is not working correctly, and showing the wrong status while internet is not connected

I'm creating a web-based application which can work offline as well as online. Therefor, I have need to check if internet is working properly or not. Currently I'm using

navigator.onLine

in JavaScript. I tried something like;

if (navigator.onLine) {
    // Internet is connected
    // work in online Mode
}
else{
    // Internet is disconnected
    // work in offline mode
}

Its work fine, but sometimes it gives wrong status. I noticed it when I change my ip and/or gateway and set them wrong in order to disconnect my internet access. No any web-page was being accessed after change my ip but navigator.onLine showing the internet status online. I restarted my system, clear browser cache, but I faced the same issue. I also read about the same issue people were facing, but didn't get a good solution. How can I solve this issue! Any Suggestions!

As mentioned in documentation for this feature:

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...

https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine

Meaning that you cannot rely on this feature to determine the connectivity. Now, it depends on your application - what you can do. One way is to have a heart-beat packets sent to some REST interface on your server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM