You can use the code below to check whether the browser can make connections to the current site:
await isOnline() // resolves to true or false
navigator.onLine
While you can use the built-in function
navigator.onLine
Show archive.org snapshot
(sic), it is only a hint for whether the device can access the Internet.
When navigator.onLine === false
you know for certain that the user device has no connection to the Internet. This means one of the following:
However, when navigator.onLine === true
we only know that the user has some form of network connection. We do not know whether the user can actually make connections. Some reasons why you may effectively be offline while navigator.onLine === true
:
The isOnline()
function below checks if you can make real requests by re-fetching your site's
favicon
Show archive.org snapshot
. If the favicon cannot be downloaded within 6 seconds, it considers your connection to be offline.
async function isOnline({ path, timeout } = {}) {
if (!navigator.onLine) return false
path ||= document.querySelector('link[rel*=icon]')?.href || '/favicon.ico'
timeout ||= 6000
const controller = new AbortController()
const timeoutTimer = setTimeout(() => controller.abort(), timeout);
try {
await fetch(path, {
cache: 'no-store',
signal: controller.signal
})
return true
} catch(error) {
return false
} finally {
clearTimeout(timeoutTimer)
}
}