Detect If Internet Connection Exists with JavaScript

There are times when the user might be browsing and loose the internet connectivity all of a sudden or user might be doing an offline browsing which comes basically from HTML 5 and the mobile apps keep the content offline for the user to read later even without internet connection. It will be very helpful if we know the user is online having an active internet connection, and the best way to Detect If Internet Connection Exists with JavaScript is by navigator property.

navigator.onLine

The navigator.onLine property provides the Boolean result (true/false) for whether or not the user is connected to the internet. Note this property works properly in all the modern browsers seamlessly, doing so in old browsers may not yield the exact result sometimes.

Syntax to use navigator.onLine

if(navigator.onLine) { 
   // Do Something
}

Hook into Events
In addition to checking the navigator property if you need to perform some operations using online and offline it is easy to hook into events.

function updateOnlineStatus() {
// Show a different icon based on offline/online

}

// Update the online status icon based on connectivity
window.addEventListener('online',  updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
updateOnlineStatus();

Detect If Internet Connection Exists with JavaScript Using XHR request

The navigator.onLine API is not much reliable and might face issues sometimes and it works efficiently with the modern browser.Alternatively, to Detect If Internet Connection Exists with JavaScript is by using XHR request to your own server or to a google server as the up-time of google would be higher.

function detectHostReachable() {

  // Handles IE and more capable browsers
  var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );
  var status;

  // Open new request as a HEAD to the root hostname with a random param to bust the cache
  xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false );

  // Issue request and handle response
  try {
    xhr.send();
    return ( xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304) );
  } catch (error) {
    return false;
  }

}

0 Shares
Leave a Reply

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

You May Also Like
XOR in Python

XOR in Python

XOR Operator in Python is also known as “exclusive or”  that compares two binary numbers bitwise if two bits are…
How To

How to configure Git proxy?

If you are working in the corporate company all the internet requests usually goes through the corporate firewall.…