Check Internet Connection Offline/Online Using JavaScript in Browser

Robin
Updated on August 13, 2022

Websites can display different types of content by checking the internet connection of a user in JavaScript. There are different techniques in JavaScript that we can follow to detect the offline or online status right inside the browser.

JavaScript has a navigator.onLine property on the window object that returns true if a user has an internet connection otherwise it returns false. But this property only runs once. To detect the connection status every time when it changes, JavaScript has the online and offline events.

You can listen to these events on the window object. When a user connects to the internet, JavaScript will fire the online event. When the user gets disconnected from the internet, the offline event will be executed.

In this article, you will see how to check the internet connection status using JavaScript inside a browser.

How to Detect Internet Connection Status in JavaScript

By detecting the internet connection status, we can show a message to our users about their connection or we can display different types of content based on their connection status.

On many websites, we see that they save some content in the browser locally and show those contents if the user has no internet connection. In this way, they let their users use the website offline.

To do so it is very important to identify the connection status of a user. Luckily we can detect it by just using some JavaScript events and properties.

Check Internet Connection Offline/Online Using JavaScript in Browser

I will show you 3 different ways in JavaScript to identify the internet online or offline status. Every method has its pros and cons. I will explain everything in detail so that you can choose the right one for your website.

  • Using the navigator.onLine property.
  • Using the offline and online events.
  • Sending HTTP requests to the server.

Let's go through each of these methods and their limitations.

Checking Internet Connection Using navigator.onLine

The navigator.onLine property is available on the browser's window object in JavaScript. We can identify the current status using this property. It returns a boolean value based on the internet connection.

  • It returns true if the user is connected.
  • If returns false if the user is not connected.

You can access this property in your JavaScript file like this:

          const showStatus = document.getElementById('show_status');

const isOnline = window.navigator.onLine;
// true or false

if (isOnline) {
    showStatus.innerText = 'You are online';
} else {
    showStatus.innerText = 'You are not online';
}
        

In this example, I have a div with an id show_status in my HTML file. I want to show whether a user is online or not. I am getting the true or false value from the window.navigator.onLine property.

If the value is true, I can create a dynamic HTML element in JavaScript and insert it inside the showStatus element or I can insert plain text.

Browser Support of navigator.onLine Property

This property has amazing browser compatibility because it is available in JavaScript for a long time. Globally, more than 98% of browsers have support for this property according to the caniuse website.

That means you don't have to worry about its support if you decide to use it.

Browser compatibility of navigator.onLine property

Even though it is widely available in almost every browser, there are also some limitations that you should know about.

Limitations of navigator.onLine property

If you check the MDN documentation for navigator.online property, you will see that they have mentioned a few problems. It's not like you will encounter bugs every time but you might face some troubles in some situations.

In some situations, this property might return true value even if the user is not connected to the internet.

  • This property returns true or false value only once when the page loads.
  • When the user's computer is running on virtualization software with virtual ethernet adapters, it will always return true.
  • If Firefox is not in the "Work Offline" mode, it will always return true even if the user is not connected to the internet.
  • If the user's computer is connected to a mobile hotspot and the internet connection in that mobile is not working then it will return a true value.

Checking Internet Connection Using offline and online Events

As you have seen earlier, the navigator.onLine property only runs once when the page loads. But if you want to notify your users as soon as they lose their connection or get the connection back.

You can listen to the online and offline events in JavaScript. Because JavaScript fires these events whenever the connection status changes.

          const showStatus = document.getElementById('show_status');

window.addEventListener('online', (e) => {
    // User is online
    showStatus.innerText = 'You are online';
});

window.addEventListener('offline', (e) => {
    // User is offline
    showStatus.innerText = 'You are offline';
});
        

You have to listen to these events on the window object. When you turn off your internet connection, the callback function in the offline event will execute automatically.

On the other hand, when you turn on the internet connection, the callback function in the online event will execute.

Note: These events will not fire when the page loads. The callback functions only execute when the network connection state changes.

Browser Support of online and offline Events

Both of these events have good browser compatibility. Most modern browsers have support for these events. Globally more than 96% of browsers can handle these events.

You can also check the browser support for online and offline events.

Online Event:

Browser compatibility of online event

Offline Event:

Browser compatibility of offline event

Limitations of offline and online Events

You might face the same problems as the navigator.onLine property in JavaScript. Those events could get executed even if there is no internet connection in some situations.

The difference between these events and the navigator.onLine property is that the property only runs once when the page loads. But these events don't get executed when the page loads.

Checking Internet Connection Using HTTP Request

If you want to make sure that your application is connected to the actual internet, not any virtualization software or hotspot then you can send an HTTP request.

The main idea is to make a request to the server or any API endpoint. Then handle the response and error if there is any. If the request gets a response successfully, the user is online. Otherwise, the user is offline.

          const checkConnection = async () => {
    try {
        const response = await fetch(
            'https://www.example.com/check-status/'
        );

        return response.status >= 200 && response.status < 300;
    } catch (error) {
        return false;
    }
};

        

I have created the checkConnection() function. This function will make the HTTP request with the fetch API. I am also using async/await syntax instead of promises. We are making the request asynchronously.

Also Read: Synchronous VS Asynchronous Programming with Examples

After getting the response from the API, we will check the status code. If the status code is equal to or greater than 200 and less than 300, the function will return true.

We can catch any error using the try/catch block. If there is an error, the function will return false.

          const showStatus = document.getElementById('show_status');

setInterval(async () => {
    const isOnline = await checkConnection();
    showStatus.innerText = isOnline ? 'You are online' : 'You are offline';
}, 10000);

        

Now, we have to use the setInterval() method to call the checkConnection() function after every few seconds. Because if we call this function directly, it will be executed only once when the page loads.

I will pass an async function as its callback function in the first argument. I am also setting 10 seconds (10000 milliseconds) as the interval delay.

Inside the callback function, I am calling the checkConnection() function with await keyword to get the response. After that, we can set the online status depending on the response.

We have set the interval to 10 seconds. So, every 10 seconds the setInterval() function will call the checkConnection() function to update the status. You can customize this interval time according to your need. You can check the connection every 20 or 30 seconds.

Limitations of HTTP Request

Using this method, you can make sure about the internet connection. But it has a few drawbacks as well.

  • You have to send an external request continuously.
  • If you maintain the server then your server will have to handle many requests.
  • If the server is down or can not handle the requests then it will show offline even if the user has an internet connection.
  • If you set the interval to 20 seconds, the users have to wait for 20 seconds to see the update after getting or losing the connection.

Which Method Should You Use?

Before choosing any of these 3 methods, you have to the requirements of your application. You already know their use cases and limitations. By matching your requirements with those, you can select.

  • If you have to check the connection for any simple logic and you need the status only once when the page loads, you can choose the navigator.onLine property.
  • If you need the internet connection status every time a user gets connected and disconnected, you have to use the online and offline events in JavaScript.
  • If you need the internet connection status whenever the status changes and you have to have the correct status in every situation then you can send an HTTP request.

Conclusion

It is very easy to detect the internet connection status using JavaScript. You have seen many methods to do so. According to your requirements, you will choose which method you want to use.

To make the selection process easier for you, I have shown you some use cases of each method. I hope you will be able to check the internet connection in JavaScript correctly for your application.

Related Posts