How to check internet connection is working or not using javascript

In this quick post I am going to show you How to check internet connection is working or not using javascript, There is a function in javascript called navigator.onLine, It’ll return true or false as the result of internet connectivity, If you are not connected with the internet it’ll return false. If internet working fine it’ll return true as output status.



Here is the simple javascript function for getting internet status working or not..

<script>
function checkInternetCon() {
var status = navigator.onLine;
if (status) {
alert("Yes!! Working");
} else {
alert("Sad!! Not Working ");
}
}</script>

Call above function on button onclick event.

<button onclick="checkInternetCon()">Check Internet Connection</button>

You can also use setInterval method in javascript to automatically check internet connectivity, As soon as internet down you can display message to visitors. Function will check for internet in every 5 sec.

setInterval(function(){ 
var status = navigator.onLine;
 if (status) {
 console.log('Working..');
 } else {
  console.log('Not Working..');
 }
}, 5000);



Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.