JavaScript: come capire con certezza se un browser è online o no

JavaScript: come capire con certezza se un browser è online o no

Per capire se un browser ha accesso ad Internet, in JavaScript occorre ricorrere ad uh workaround.

La proprietà booleana navigator.onLine non è del tutto affidabile in quanto la sua implementazione varia da browser a browser. La documentazione afferma:

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.

Il workaround consiste nel provare ad effettuare una richiesta AJAX verso un endpoint del nostro sito o di un altro sito che disponga di API accessibili lato client e verificare che abbia un esito positivo.


'use strict';

const isOnline = endpoint => {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.onload = () => {
            resolve(true);
        };
        xhr.onerror = () => {
            reject(false);
        };
        xhr.open('GET', endpoint, true);
        xhr.send();
    });
};

Torna su