-1

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!

Dropout
  • 13,653
  • 10
  • 56
  • 109
  • The onLine preference only check if the browser is in offline mode or not. I think that you would have to perform a webrequest to find out if the computer is online or not – bvx89 Jan 27 '14 at 15:26

4 Answers4

2

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

}
user2423959
  • 836
  • 1
  • 13
  • 27
1

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.

scunliffe
  • 62,582
  • 25
  • 126
  • 161
0

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

Chrome Linux - Always returns true Is it help you?

vadim.zhiltsov
  • 9,294
  • 2
  • 15
  • 16
0

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 }

Knights
  • 1,467
  • 1
  • 16
  • 24