Check internet connection using JavaScript

	<script>
          function doesConnectionExist() {
    var xhr = new XMLHttpRequest();
    var file = "https://www.instadiet.in/image/catalog/456.png";
    var randomNum = Math.round(Math.random() * 10000);
 
    xhr.open('HEAD', file, true);
    xhr.send();
     
    xhr.addEventListener("readystatechange", processRequest, false);
 
    function processRequest(e) {
      if (xhr.readyState == 4) {
        if (xhr.status >= 200 && xhr.status < 304) {
          console.log("connection exists!");
        } else {
          console.log("connection doesn't exist!");
        }
      }
    }
}
          setInterval(function(){ 
          doesConnectionExist();
          var ifConnected = window.navigator.onLine;
if (ifConnected) {
  console.log('Connection available');
} else {
  console.log('Connection not available');
}
           }, 3000);</script>

Leave a Reply