How To Check If User Is Offline Using JavaScript

JavaScript

29/07/2021


The browser provides an API that allows us to check its connection to a network: navigator.onLine.

JAVASCRIPT
if (navigator.onLine) alert('Online')
else alert('Offline')

Be aware that I said to a network, not the internet! 🚨 To avoid a false positive, I therefore recommend adding a second check:

JAVASCRIPT
async function hasInternet() {
try {
await fetch('https://google.com')
return true
} catch (error) {
return false
}
}

This second check is done by carrying out a simple GET request to any website. In our example it's google.com, but in general the response should contain as little data as possible.

If we are unable ❌ to reach the site, the request throws an error, which means we're not connected to the internet.

Lastly, let's integrate our check into the IF statement:

JAVASCRIPT
// Inside async function
if (navigator.onLine && await hasInternet()) alert('Online')
else alert('Offline')

WRITTEN BY

Code and stuff