🚀 Detecting If a User is Online/Offline with JavaScript
Niall Maher

Niall Maher @nialljoemaher

About: Owner @ Codú, JavaScript Developer, mentor and a lifelong learner. Tweet @nialljoemaher

Location:
Dublin, Ireland
Joined:
May 10, 2019

🚀 Detecting If a User is Online/Offline with JavaScript

Publish Date: Jun 25 '20
313 25

As developers, we sometimes get used to our great broadband in our offices and localhost being the fastest site ever with no network issues.

In fact, what a lot of people forget is just over half of all internet traffic is driven over mobile phones and unless you are in a booming city, a consistent internet connection is not all that normal.

This is the first episode in a series which I am going to go over some tips and tricks to easily create a better experience for people who have a bad internet connection. Which if you are building consumer-facing applications could be a huge portion of your users.

In this post, we are going to look at a super-easy way to check if the user is connected to the internet and detect if they lose connection or reconnect so that you can update your UI appropriately depending on the internet status.

Online and offline banner


You can watch my video explanation (where I go into more detail) here or scroll on to keep reading. 💜


By the end of this post, you will have cards that change based on if the user has internet.

First a little bit of boilerplate

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Network Checker</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="app">
      <h1 class="status">Hello</h1>
    </div>
    <script src="app.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

style.css

body {
  background-color: #555;
}

.app {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

.status {
  padding: 40px;
  min-width: 120px;
  border-radius: 20px;
  background-color: #eee;
  text-align: center;
  font-size: 80px;
}

.status.online {
  border: 8px solid #41a700;
  color: #41a700;
}

.status.offline {
  border: 8px solid #f15c4f;
  color: #f15c4f;
}
Enter fullscreen mode Exit fullscreen mode

Add an empty app.js file and that's where we will be doing all of the work.

So your folder should look like this:

├── app
│   ├── index.html
│   └── style.css
│   └── app.js

Enter fullscreen mode Exit fullscreen mode

Let's first create a function to manipulate the DOM based on if the user has connectivity. We will pass it a boolean value.


function hasNetwork(online) {
  const element = document.querySelector(".status");
  // Update the DOM to reflect the current status
  if (online) {
    element.classList.remove("offline");
    element.classList.add("online");
    element.innerText = "Online";
  } else {
    element.classList.remove("online");
    element.classList.add("offline");
    element.innerText = "Offline";
  }
}

Enter fullscreen mode Exit fullscreen mode

Next is the fun part.

We will first use navigator.online to check if the user has internet when the page initially loads. The navigator.online has supported all the way back to IE9 and returns a boolean value.

It is important to remember that browsers implement this feature differently and for more detailed information view the MDN docs here.

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet.

// Listen for the page to be finished loading
window.addEventListener("load", () => {
  hasNetwork(navigator.onLine);
});
Enter fullscreen mode Exit fullscreen mode

Note 📝

This can at first seem like a pointless step but with the current state of web development tools and best practices, you will find often users have web pages cached and will still be able to access your site offline. So this initial check can be great if they boot up your app and can be made aware their content may be out of date.

The next thing we will do is add the event listeners for the online and offline events so that we can check when the users' network status changes.

There are two events we care about and that's online and offline. As I'm sure you can guess, these are triggered when a user switches between offline and online.

window.addEventListener("load", () => {
  hasNetwork(navigator.onLine);

  window.addEventListener("online", () => {
    // Set hasNetwork to online when they change to online.
    hasNetwork(true);
  });

  window.addEventListener("offline", () => {
    // Set hasNetwork to offline when they change to offline.
    hasNetwork(false);
  });
});
Enter fullscreen mode Exit fullscreen mode

Now when we go into our app we will get live feedback when the user changes their network status.

Showing what the status changing would look like

So when to use this?

Maybe you need to tell a user they can't upload a file because they are offline, the live data they are seeing may no longer be up to date because they are offline or anything really. There's dozens of reason you may need to detect the network status and as web developers let's try to make the web a more user-friendly experience for everyone.

I hope this tip helped and until the next one, happy coding! 💜


Follow me on Twitter

Subscribe on Codú Community

Comments 25 total

  • Jr. Dev 👨🏾‍💻
    Jr. Dev 👨🏾‍💻Jun 25, 2020

    Awesome post. It's not something I have really thought about before but I will start doing now

    • Niall Maher
      Niall MaherJun 25, 2020

      Yes, definitely something to look into 😁

  • АнонимJun 25, 2020

    [deleted]

  • Abdul Ghani
    Abdul GhaniJun 25, 2020

    Awesome! 😁

  • Ben Halpern
    Ben HalpernJun 25, 2020

    Great explanation. I feel like this really contextualizes how to implement this.

    • Niall Maher
      Niall MaherJun 25, 2020

      Thanks Ben! Glad you enjoyed it. 💜

  • Ravikiran
    RavikiranJun 26, 2020

    Awesome

  • Amine M
    Amine MJun 27, 2020

    This is cool, thanks for sharing with us Niall

  • TrasherDK
    TrasherDKJun 27, 2020

    While the navigator.onLine thingy is a neat trick, it's not that useful information.

    Knowing if connections to back-end services are up/down would be something.

  • Shaiju T
    Shaiju TJun 27, 2020

    Thanks, Short and to the point article. I think most PWA apps does this.

    • Niall Maher
      Niall MaherJun 27, 2020

      Not without diving into a service worker. It'll also only catch when network requests succeed/fail so you could add this to a PWA to create a richer experience. So this will actually update your UI when your connectivity changes rather than when you're actually making requests.

  • timothyokooboh
    timothyokoobohJun 27, 2020

    Thank you Niall. I have learned something new.

  • Param Siddharth
    Param SiddharthJun 27, 2020

    That will help a lot! :)
    I wonder, is there a straightforward implementation to verify whether or not Internet is accessible when "online"?

    • Niall Maher
      Niall MaherJun 27, 2020

      When it comes to the actual network requests and that I find service workers are one of the best ways to serve up different things based on failed requests.

  • Adeyemi Taiwo
    Adeyemi TaiwoJun 27, 2020

    Great tutorial! Thanks for sharing.

  • dvg3012
    dvg3012Jun 27, 2020

    Nice explanation!
    Nevertheless, I recently had to implement such a feature and found the navigator online/offline not really reliable. Especially if you've to support different devices, browsers, OS and Frameworks(Electron, Cordova,...).
    I went with a workaround consisting of the navigator API and a fetch request to an external endpoint to really make sure a connection exists.
    Hope this helps, if someone struggles with the raw navigator API.

    • Niall Maher
      Niall MaherJun 27, 2020

      Totally agree, this isn't a silver bullet! This is just one of the ways to handle things. I use this combined with service workers and error handling.

  • Dieter Geerts
    Dieter GeertsJun 29, 2020

    navigator.online on it's own for checking if a user is really online is not working. It only lets you know if there is network access, which isn't the same as "connected to the internet". So basically, it is useless, unless you application works in a closed off network or something....

    • Niall Maher
      Niall MaherJun 29, 2020

      I've left a link to some of the issues with navigator.online in the article. Definitely not a good solution alone. The event listeners are the real magic for checking when people are using apps on the move.

  • Luddite
    LudditeApr 22, 2021

    navigator.online cannot be trusted: there's the "liefi" situation where you appear to be online but still cannot access the internet.

  • hanzlahabib
    hanzlahabibSep 30, 2021

    It really don't work for network disconnect, it only listens to dev tool throttling, please confirm if anyone else have faced this issue

    also MDN web docs state it's isn't fully reliable for checking & they recommend to use XHR response for network offline confirmation

    Thanks

Add comment