How to Check Internet Connection Status in Javascript
By FoxLearn 11/5/2024 1:55:58 AM 79
It returns a Boolean value that indicates whether the browser is connected to the internet (true) or not (false).
For example:
if (navigator.onLine) { console.log("You are online!"); } else { console.log("You are offline!"); }
You can also listen for changes in the internet connection status by using the online
and offline
events.
// Listen for when the browser goes online window.addEventListener('online', function() { console.log("You are back online!"); }); // Listen for when the browser goes offline window.addEventListener('offline', function() { console.log("You are offline!"); });
The navigator.onLine
property only indicates if the browser is connected to a network, but it doesn't confirm if there's actual internet access. A device might be connected to a local network without being able to reach the internet.
If you want to test whether you can reach a specific server or domain (for instance, Google), you might need to make a network request, such as an AJAX or fetch request, to verify connectivity beyond the network connection itself.
For example:
function checkInternetConnectivity() { fetch('https://www.google.com', { method: 'HEAD', mode: 'no-cors'}).then((response) => { console.log("connected"); }, (err) => { console.log("error: " + err); // (currently fetch failed) }); } //Test checkInternetConnectivity();
This method helps ensure that not only is the device connected to a network, but it also has access to the broader internet.