Using JavaScript code to Check if the Internet Connection is Available

Introduction

If there is ever a moment when you need your internet connection to work, there is a very good chance it is at that very moment your internet connection will fail.

In this post 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:

<html>  
<head>  
<title>internet check</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>  
</head>  
<body>  
<div class="container">  
<div class="row">  
<span>Click on the button to check the internet available or not</span> <button type="button" class="btn btn-success" onclick="internetCheck()">Try</button>  
</div>  
<span id="internetCheck"></span>  
</div>  
<script>  
function internetCheck() {  
  var value = "Is the browser online? " + navigator.onLine;  
  document.getElementById("internetCheck").innerHTML = value ;  
}  
</script>  
  
</body>  
</html>  

Summary

More and more of your sites and apps store state in a remote location. Having an internet connection at all times when using your phone or computer or whatever is no longer a luxury for many parts of the world. It is a necessity.

For those moments when your site or app doesn’t have an internet connection that it desperately relies on, this code provides you with a basic solution for how to start dealing with it.

I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others. Thank you !

#javascript #tutorial #developer #programming

Using JavaScript code to Check if the Internet Connection is Available
1 Likes21.30 GEEK