2

I want to check if network connection exists at runtime in javascript. I am using window.navigator.onLine but its not working.

<script language="javascript">

alert(window.navigator.onLine);

</script>

it is returning true always

Jonathan Naguin
  • 14,526
  • 6
  • 46
  • 75
manishkr1608
  • 313
  • 1
  • 3
  • 13
  • Which browser are you in? Different browsers have different implementations. Have a read of this https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.onLine In chrome for instance if you can connect to your router it considers you online, even if you don't have an internet connection – Jerryf Aug 06 '13 at 08:39

2 Answers2

0

You could try using an AJAX call with a short timeout and handling the success/error.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
0

You can do it as below :

if (navigator.onLine) {
    alert("online");
}

or as below :

var xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', state_change, true);
xhr.open("GET", url, true);
xhr.send(null);

function state_change(){
   if(xhr.readyState == 4){
        if(xhr.status == 200){
          console.log('worked'); 
        } else if(xhr.status == 0) {
          console.log('no internet'); 
        } else {
          // Some other error
        } 
   }
}
Butani Vijay
  • 4,181
  • 2
  • 29
  • 61