Skip to content
Related Articles

Related Articles

Improve Article

How to detect the Internet connection is offline or not using JavaScript?

  • Last Updated : 28 Jan, 2020

In some cases, it is necessary to determine whether the browser is online or offline before performing a required task. Many developers use AJAX to determine the connection status of the browser (online or offline) by sending a request to the server. However, this is not a good method for determining the state of the browser because it requires bandwidth and can also affect usability.

Yet JavaScript’s Browser Object Model(BOM) provides a direct way to detect browser’s connectivity status i.e. whether the browser is online or offline.

To perform this check, targeting all possible browsers out there, we will be using the following property :

navigator.onLine

Syntax:



function isOnline() { 
    return ( navigator.onLine) 
}

Example: This example displays a button if it is clicked, It will show the connectivity status.




<!DOCTYPE html>
<html>
  
<body>
  
    <p>Click the button to check 
      if the browser is online.</p>
  
    <button onclick="isOnline()">
      Click Me
  </button>
  
    <p id="demo"></p>
  
    <script>
        function isOnline() {
  
            if (navigator.onLine) {
                document.getElementById(
                  "demo").innerHTML = "Online";
            } else {
                document.getElementById(
                  "demo").innerHTML = "Offline";
            }
        }
    </script>
  
</body>
  
</html>

Note: The minimum version of browsers that supports the property:

  • Google Chrome: 14.0
  • Internet Explorer: Yes
  • Firefox: 3.5
  • Safari: 5.0.4
  • Opera: Yes

Output:
Output

Attention reader! Don’t stop learning now. Get hold of all the important Comcompetitivepetitve Programming concepts with the Web Design for Beginners | HTML  course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :