loading...
Cover image for πŸš€ Detecting If a User is Online/Offline with JavaScript

πŸš€ Detecting If a User is Online/Offline with JavaScript

nialljoemaher profile image Niall Maher ・4 min read

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>

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

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

Posted on by:

nialljoemaher profile

Niall Maher

@nialljoemaher

Owner @ CodΓΊ, JavaScript Developer, mentor and a lifelong learner. Tweet @nialljoemaher

Discussion

pic
Editor guide
 

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

 

Yes, definitely something to look into 😁

 

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.

 

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.

 

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....

 

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.

 

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

 

Thanks Ben! Glad you enjoyed it. πŸ’œ

 

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

 

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.

 

Thank you Niall. I have learned something new.

 

Glad it helped 😁

 

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

 

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.

 

Great tutorial! Thanks for sharing.

 

Awesome! 😁

 

Thanks πŸ’œ

 
 

Cheers πŸ’œ

 

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.

 

This is cool, thanks for sharing with us Niall

 

Glad you enjoyed it!

 
[deleted]