How to detect if browser is offline in 2018?

2.9k Views Asked by At

There used to exist offline.js for detection of a connection, but that project is no longer maintained. Also, the browser's 'navigator.onLine' property is notoriously unreliable.

What is the best/most up-to-date method to use to actively detect the browser's online state, compatible with modern browsers including mobile device browsers, that can raise various events when the online status changes? Do I need to write this myself, or is that reinventing the wheel?

Note that nobody in my userbase is going to be changing the "Work Offline" setting in the browser in order to go online/offline. Instead, they will be unplugging network cables, disconnecting from wifi networks, driving to locations where no signals are available, etc.

My thought was to simply set up a timeout to repeatedly make AJAX calls to a URL on my server, and simply set an 'online' variable to true/false as well as call online/offline callback functions based on error/success of the AJAX call. Is that the recommended way?

3

There are 3 best solutions below

6
Imal Hasaranga Perera On

simply use

navigator.onLine

see the browser support https://caniuse.com/#feat=online-status

0
Benjamin Udu On

Use

`var wentOffline, wentOnline;
 function handleConnectionChange(event){
    if(event.type == "offline"){
        console.log("You lost connection.");
        wentOffline = new Date(event.timeStamp);
    }
    if(event.type == "online"){
        console.log("You are now back online.");
        wentOnline = new Date(event.timeStamp);
        console.log("You were offline for " + (wentOnline — wentOffline) / 1000 + "seconds.");
    }
}
window.addEventListener('online', handleConnectionChange);
window.addEventListener('offline', handleConnectionChange);`

Check the post: https://medium.com/@MateMarschalko/online-and-offline-events-with-javascript-d424bec8f43

2
JavaScript Bee On

I worked on a similar implementation and this was my solution using setInterval and fetch API. There will be 2 functions, first function will run for every 30 seconds checking internet connection. A flag variable is set to true which will control the function execution. In case of disconnection, the second function will be invoked to call fetch API for every 5 seconds. If successfully connected, the flag is set to true so the first function can be executed again for every 30 seconds and the interval is cleared.

doesConnectionExist: function() {
setInterval(function () {
if(flag === true){
let randomNum = Math.round(Math.random() * 10000);
let url = "test.js?rand=";
const response = fetch(url + randomNum)
                .then(function () {
                    clearInterval(interval);
                })
                .catch(function () {
                     console.log("You are currently offline.");
                     interval = setInterval(function () { checkForConnectivity(); }, 5000);
                });
}
}, 30000);
}

checkConnectivity: function() {
flag = false;
let randomNum = Math.round(Math.random() * 10000);
let url = "test.js?rand=";
const response = fetch(url + randomNum)
                .then(function () {
                    console.log("Your Internet connection was restored.");
                     clearInterval(interval);
                     flag = true;
})
.catch(function () {
                    return null;
                });
};