How to check the internet connection status in JavaScript

In this tutorial, we are going to see how to check the internet connection on our browser using JavaScript so that it is possible to see if online or offline. Checking the internet availability is easy in JavaScript.

To check the internet connection status we are going to use the JavaScript navigator onLine property:

window.navigator.onLine

It will return a boolean true or false depending on the internet status. If the browser is connected to the internet, it will return the boolean true value and if not then it will return the boolean false value.

Below is a simple code example which will alert a message which tells us if the internet connection available or not:



var ifConnected = window.navigator.onLine;
if (ifConnected) {
  alert('Connection available');
} else {
  alert('Connection not available');
}

It will simply alert message. If the internet status change, it will not show the alert message again to inform us. After we reload or refresh the page, it will show the internet connection status.

Run your JavaScript code every n seconds using setInterval() method

What is the opposite of JavaScript push() method that works reverse?

Now, if we want to see the status change message with the internet connection close or start without page reload, then below is the JavaScript code that can do this:

  var ifConnected = window.navigator.onLine;
    if (ifConnected) {
      document.getElementById("checkOnline").innerHTML = "Online";
      document.getElementById("checkOnline").style.color = "green";
    } else {
      document.getElementById("checkOnline").innerHTML = "Offline";
      document.getElementById("checkOnline").style.color = "red";
    }

setInterval(function(){ 

  var ifConnected = window.navigator.onLine;
    if (ifConnected) {
      document.getElementById("checkOnline").innerHTML = "Online";
      document.getElementById("checkOnline").style.color = "green";
    } else {
      document.getElementById("checkOnline").innerHTML = "Offline";
      document.getElementById("checkOnline").style.color = "red";
    }

 }, 3000);

The above code will check the internet status every 3 seconds and it will set the status text to our paragraph. Below is the HTML of our paragraph:

<p id="checkOnline"></p>

When we run the code on our browser then when the network will be available, it will show a green text and when it will be offline, then it will show a red text.

Leave a Reply

Your email address will not be published. Required fields are marked *