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

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


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

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.