1

it is possible to know when user has internet connection and when no. I've tried this:

window.addEventListener('online', () => {
  // some stuff
}, false);

window.addEventListener('offline', () => {
  // some stuff
}, false);

as well have tried window.navigator.online.

All above things works fine just when go to network tab from developer tools and disable/enable it, but it doesn't work when you go and disable WiFi or turn off the router for example.

It is possible somehow to subscribe to this network changes in js?

Many thanks!

1

2 Answers 2

2

You can use an interval to mimic these events:

var isOnline = true;
setInterval(function(){
    if(!isOnline && navigator.onLine){
        isOnline = true;
        console.log("Back online!");
    }
    else if(isOnline && !navigator.onLine){
        isOnline = false;
        console.log("Lost connection!");
    }
}, 100);
2
  • 1
    Thanks for idea man, but this isn't gonna work as well. Try to write in console navigator.online, it will show -> true. Than go and turn off internet connection and run again navigator.online in console. You will see that it still shows -> true instead of false. Commented Jan 2, 2020 at 20:30
  • It shows false for me. How exactly are you turning off internet? Commented Jan 2, 2020 at 20:48
1

online = window.navigator.onLine;

check your case.

that will return a bool.

see more: link

2
  • 1
    this is not gonna work if you turn off manually your internet. Commented Jan 2, 2020 at 17:13
  • yeh, it does not really check internet availability. I would use an ajax call to test. @ExariConstantin Commented Jan 2, 2020 at 17:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.