JavaScript : window offline event not firing on Android phones (not in Android Browser or Chrome) and navigator.onLine Return always true

453 views Asked by At

JavaScript navigator.onLine command suddenly stop working on Android phones, not in Android Browser, also not in Chrome!

In Android Galaxy, as soon as you put on flight mode (or there is no internet), you get a notification that there is no internet in the following code - but you immediately get a message as if the internet is back.

The following code for example stopped working:

        window.addEventListener('offline', function (e) {
            alert('offline');
        });
        window.addEventListener('online', function (e) {
            alert('online');
        });

And

navigator.onLine

always returns true!

Does anyone have any idea, why is this happening?

Check it yourself on Android: https://codepen.io/Zvi-Redler/pen/JjeMLWR

Or an idea how to get around the problem in the meantime?

(Our QA team found, checked on several devices, we don't know about a special update. I do airplane mode, for sure there is no network and in the past it worked.)

3

There are 3 answers

3
Codemaster United On

First window's offline event, it fires when there is a network change. Second, navigator.onLine, it returns the current status of the network. Both are different.

On Samsung Galaxy J7 (2015), Chrome 104 it is working properly. After I load the page and turn off the data, an alert with the current network state is appearing, so window offline event working properly. And on clicking the button, navigator.onLine is return true, if I'm online, else returning false.

Everything seems to work fine.

1
Wakil Ahmed On

You can try using a combination of other events to detect the online/offline status like the online and offline events on the document object, along with a periodic check using setInterval to monitor the network status.

function checkOnlineStatus() {
  if (navigator.onLine) {
    alert('Online');
  } else {
    alert('Offline');
  }
}

checkOnlineStatus();

// Check online status as needed
setInterval(checkOnlineStatus, 2000);

// Listen for the 'online' and 'offline' events
document.addEventListener('online', function() {
  alert('Online');
});

document.addEventListener('offline', function() {
  alert('Offline');
});
1
s1ddiq On
window.addEventListener('offline', function (e) {
  alert('offline');
});

IS NOT EQUAL TO navigator.onLine

just keep your function and remove the navigation.onLine