DEV Community

Karel De Smet
Karel De Smet

Posted on • Originally published at kareldesmet.be

Detecting if your user is online or offline

At work, we're developing a PWA (amongst others) and as a new feature, we needed to warn users when they are offline. This should incentivise them to first restore their network connection before taking further action, avoiding possible unwanted side effects from being offline.

After testing, I had a look at how it was implemented and was pleasantly surprised.

Navigator.onLine

The Navigator object, which you can access in the browser via window.navigator, has an onLine property. This boolean is prone to false positives, but we weren't looking for perfect coverage on this one.

Mind the capital 'L' though!

  
  window.navigator.online
  // undefined

  window.navigator.onLine
  // true
  

Online and offline events

So we know how to check if a user is online or offline. But how can we detect changes? Writing custom events has never been anyone's favorite, but luckily the online and offline events are readily available.

Want to try it out? Copy and paste the following code into an HTML file and open it in the browser. Then play with your network connection (in your OS or your browser's DevTools) to see it in action.

  
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Online/offline</title>
      </head>
      <body>
        <h1 id="status"></h1>
      </body>
      <script>
        function userIsOnline() {
          document.getElementById("status").textContent = "User is online";
        }

        function userIsOffline() {
          document.getElementById("status").textContent = "User is offline";
        }

        if (window.navigator.onLine) {
          userIsOnline();
        } else {
          userIsOffline();
        }

        window.addEventListener("online", userIsOnline);
        window.addEventListener("offline", userIsOffline);
      </script>
    </html>
  

NetworkInformation

Although out of scope for our use case, it was interesting to discover window.navigation.connection contained more network goodies, in the form of a NetworkInformation instance.

In my case, it contained the following:

  
  downlink: 10,
  effectiveType: "4g",
  rtt: 50,
  saveData: false
  

Huh, my downlink seems slow as hell? It's supposed to represent my download speed in Mbps but it's not even close to what I would expect.

Well, it seems like Chrome arbitrarily caps this value at 10 as an anti-fingerprinting measure.

Well, thank you Google for keeping me safe and secure ;)

Discussion (0)