Check If Internet Exists In JavaScript

Introduction

 
In this blog and code example, we will use JavaScript code to check if the Internet connection is available or not on a machine. The JavaScript can be placed in a Web page. 
 
JavaScript Navigator.OnLine property it used to check if the Internet connection is available on a machine or not. It returns a true value if the internet is available. It returns false of the internet is not available. 
 
The following code example is an HTML web page that uses navigator.OnLine property on a button clicks to check the internet connection.
 
Example:
  1. <html>  
  2.   
  3.      <head>  
  4.           <title>internet check</title>  
  5.           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">  
  6.           <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>  
  7.           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>  
  8.      </head>  
  9.   
  10.      <body>  
  11.           <div class="container">  
  12.                <div class="row">  
  13.                     <span>Click on the button to check the internet available or not</span> <button type="button" class="btn btn-success" onclick="internetCheck()">Try</button>  
  14.                </div>  
  15.                <span id="internetCheck"></span>  
  16.           </div>  
  17.           <script>  
  18.           function internetCheck() {  
  19.                var value = "Is the browser online? " + navigator.onLine;  
  20.                document.getElementById("internetCheck").innerHTML = value;  
  21.           }  
  22.           </script>  
  23.      </body>  
  24.   
  25. </html> 

Summary

 
In this simple blog, we learned how can we create a Web app to check internet availability.