Detecting If a User is Online/Offline with JavaScript 💻

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, many people forget that 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.

In this post, we will 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>

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;
}

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

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";
  }
}

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

Note 📝

This can initially seem like a pointless step, but with the current state of web development tools and best practices, you will find users often have web pages cached and can still 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.

Next, we will add the event listeners for the online and offline events to check when the users' network status changes.

There are two events we care about: 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);
  });
});

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 are dozens of reasons 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ú.

JavaScriptTutorialWeb Development
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.