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;
  }

}
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Sort Dictionary By Value In Python

Sort Dictionary by value in Python

Table of Contents Hide Python sorted() function to rescueSyntax: sorted(iterable, key, reverse)Sort a Dictionary by ValueExample 1: Basic Sorting in PythonExample 2 : Sorting different Data Types in PythonExample 3: Sort…
View Post
[Solved] Err_Http2_Protocol_Error

[Solved] err_http2_protocol_error

Table of Contents Hide Solution err_http2_protocol_errorScenario 1: Low Disk SpaceScenario 2: Gzip double compressionScenario 3: Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR after upgrading to VS 2019 16.10.0 (and 16.10.1) The err_http2_protocol_error…
View Post
Node.js

Node.js Environment Setup

Table of Contents Hide NodeJS Installation Video TutorialInstalling Node.js and npm on Windows Operating SystemInstalling Node.js and npm on MacInstalling Node.js using XCode and HomebrewInstall Node.js on Ubuntu It’s very…
View Post