Posted 3 months ago. Visible to the public.

JavaScript: Testing whether the browser is online or offline

You can use the code below to check whether the browser can make connections to the current site:

Copy
await isOnline() // resolves to true or false

Limitations of navigator.onLine

While you can use the built-in function navigator.onLine Archive (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:

  • no WLAN network is connected and Ethernet cable is plugged in
  • the user has explicitly switched to offline mode (a feature offered by some browsers)
  • the user has enabled airplane mode on their phone
  • the user is emulating an offline connection using their browser's DevTools

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:

  • Your phone reports a network connection, but your mobile data plan is exhausted.
  • Your phone reports a network connection, but you just drove into a tunnel that blocks phone signals.
  • You have a network connection, but it's so slow that you're effectively offline ( "lie-fi" Archive ).
  • You have a network connection, but limited to the local network.

The isOnline() function below checks if you can make real requests by re-fetching your site's favicon Archive . If the favicon cannot be downloaded within 6 seconds, it considers your connection to be offline.

The code

Copy
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) } }

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Avatar
Henning Koch
Last edit:
3 months ago
by Emanuel De
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more