How to detect the Internet connection is offline in JavaScript?
The problem of some methods like navigator.onLine
is that they are not compatible with some browsers and mobile versions, an option that helped me a lot was to use the classic XMLHttpRequest
method and also foresee the possible case that the file was stored in cache with response XMLHttpRequest.status
is greater than 200 and less than 304.
Here is my code:
var xhr = new XMLHttpRequest();
//index.php is in my web
xhr.open('HEAD', 'index.php', true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
//If you use a cache storage manager (service worker), it is likely that the
//index.php file will be available even without internet, so do the following validation
if (xhr.status >= 200 && xhr.status < 304) {
console.log('On line!');
} else {
console.log('Offline :(');
}
}
}