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
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
You could try using an AJAX call with a short timeout and handling the success/error.
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
}
}
}