DEV Community

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

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

Niall Maher
Owner @ CodΓΊ, JavaScript Developer, mentor and a lifelong learner. Tweet @nialljoemaher
・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


<!DOCTYPE html>
<html lang="en">
    <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" />
    <div class="app">
      <h1 class="status">Hello</h1>
    <script src="app.js"></script>
Enter fullscreen mode Exit fullscreen mode


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;
} {
  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.innerText = "Online";
  } else {
    element.innerText = "Offline";

Enter fullscreen mode Exit fullscreen mode

Next is the fun part.

We will first use to check if the user has internet when the page initially loads. The 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", () => {
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", () => {

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

  window.addEventListener("offline", () => {
    // Set hasNetwork to offline when they change to offline.
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

Discussion (24)

jrdev_ profile image
Jr. Dev πŸ‘¨πŸΎβ€πŸ’»

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

nialljoemaher profile image
Niall Maher Author

Yes, definitely something to look into 😁

dvg3012 profile image

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.

nialljoemaher profile image
Niall Maher Author

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.

dietergeerts profile image
Dieter Geerts 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....

nialljoemaher profile image
Niall Maher Author

I've left a link to some of the issues with 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.

shaijut profile image
Shaiju T

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

nialljoemaher profile image
Niall Maher Author

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.

ben profile image
Ben Halpern

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

nialljoemaher profile image
Niall Maher Author

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

adeyemitj profile image
Adeyemi Taiwo

Great tutorial! Thanks for sharing.

ravikiran profile image


nialljoemaher profile image
Niall Maher Author

Cheers πŸ’œ

trasherdk profile image

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.

ineam profile image

This is cool, thanks for sharing with us Niall

nialljoemaher profile image
Niall Maher Author

Glad you enjoyed it!

timothyokooboh profile image

Thank you Niall. I have learned something new.

nialljoemaher profile image
Niall Maher Author

Glad it helped 😁

paramsiddharth profile image
Param Siddharth

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

nialljoemaher profile image
Niall Maher Author

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.

abdulghani200 profile image
Abdul Ghani

Awesome! 😁

nialljoemaher profile image
Niall Maher Author

Thanks πŸ’œ

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

Sloan, the sloth mascot
Comment deleted