The Mysterious Tale of Internet Connection Detection

The Mysterious Tale of Internet Connection Detection

Unveiling the Magic with Just a Dash of JavaScript!

·

4 min read

This is my story. Recently while using the internet and browsers, before me becoming a programmer, I’ve always wondered how websites knew when I lost connection to the vast digital realm(the internet has proven to be much bigger than a digital realm nowadays 🤔). In the early days, websites were oblivious to the connection status of their visitors. They sat idly, hoping for the best, while users cursed their screens in frustration. I could imagine the level of user experience then. Anyways, let’s take a walk to the present, a humble hero named JavaScript stepped into the scene. I’m going to break down the concept of how you can detect the status of a user’s internet connection programmatically in ReactJS and JavaScript.

JavaScript introduced the concept of the navigator object, which holds valuable information about the user's browser and system. Among its secrets lies a powerful property called online. With a flick of code, websites gained the ability to tap into this mystical property and determine if their visitors were surfing the waves of the internet or lost in a sea of disconnection.

But how does JavaScript keep track of the ever-changing online status? Through the power of event listeners! With great anticipation, websites listen to two key events: 'online' and 'offline'. Like loyal servants, these events fire whenever the user's connection status changes, allowing websites to react accordingly.

Let’s look at some code samples;

Here are the steps to take:

  • Use the navigator.onLine property in your React components to check the browser's online status. It returns true if the browser is connected to the internet and false otherwise.

  • Create a component or function that listens for changes in the online status. You can use the window.addEventListener method with the 'online' and 'offline' events to detect when the online status changes. For example:

      import React, { useState, useEffect } from 'react';
    
      function App() {
        const [isOnline, setIsOnline] = useState(navigator.onLine);
    
        useEffect(() => {
          function handleOnlineStatus() {
            setIsOnline(navigator.onLine);
          }
    
          window.addEventListener('online', handleOnlineStatus);
          window.addEventListener('offline', handleOnlineStatus);
    
          return () => {
            window.removeEventListener('online', handleOnlineStatus);
            window.removeEventListener('offline', handleOnlineStatus);
          };
        }, []);
    
        return (
          <div>
            {isOnline ? <p>You are online</p> : <p>You are offline</p>}
          </div>
        );
      }
    

    This code sets up event listeners for online and offline events and updates the isOnline state accordingly.

This is just one step towards demystifying internet connectivity detection, but we have a problem. ☹️

“This navigator.online() property is unreliable.”

A computer can be connected to a network without having Internet access. The navigator.onLine property relies on the browser's own understanding of the connection status. It's worth mentioning that some browsers may not accurately reflect the true connectivity state due to various factors, such as network configuration or browser quirks. This means that navigator.onLine can occasionally report incorrect results, leading to false positives or false negatives.

This is where server-side detection comes into play. To ensure a more robust internet connection detection mechanism, it's advisable to combine client-side techniques with server-side checks. By leveraging both approaches, you can achieve a more comprehensive and reliable solution.

On the client-side, you can still utilize navigator.onLine as a quick initial check, but you should also listen for the 'online' and 'offline' events to actively track changes in the connection status. This helps capture real-time updates and provides a more accurate reflection of the user's connectivity.

Meanwhile, on the server-side, you can employ techniques like making HTTP requests to external services or pinging known servers to verify your own connection to the internet. These server-side checks act as an additional layer of confirmation, ensuring that your application is aware of the true connectivity state.

I’ll be covering lots of ways or tricks on how you can detect your internet connection status in Node JS in another article. Several other packages and libraries can serve a similar purpose or provide additional functionalities.

Remember, the internet is a complex and ever-changing landscape, and reliable connection detection can be a challenge. By employing a combination of client-side and server-side techniques, you'll be better equipped to handle varying scenarios and deliver a more robust experience to your users.