Question

Is there a way to check internet connection using pure JavaScript, without requesting something from the web? I've tried to use

alert(navigator.onLine);

but it always returns true.

Thanks!

Was it helpful?

Solution

Depending on what you are trying to achieve this may be a lost cause. Having an Internet Connection 1 second does not mean you will have it the next (think mobile, spotty networks, dropped packets, tunnels, congested conference/airport wifi etc.)

You are better off to make an asynchronous request for the resource you want... if it works... Giddy Up!... if it fails, or times out, then deal with that scenario.

OTHER TIPS

please try the below code and update if it is working

function hostReachable() {


  var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );
  var status;

  xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false );


  try {
    xhr.send();
    return ( xhr.status >= 200 && xhr.status < 300 || xhr.status === 304 );
  } catch (error) {
    return false;
  }

}

Please look follow link: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine.onLine

Chrome Linux - Always returns true Is it help you?

navigator.onLine checks to see if you are online or offline, it returns true if you are online which is similar to saying that you have an active internet connection going on. it returns false if you are not online which is similar to saying you do not have an active internet connection

so you can do something like this below if your app needs to detect connection:

if(navigator.onLine) { //do something }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top