According to MDN there are both events online
and offline
, so you can instantly detect changes and know the status whenever you need it without needing to setTinterval
.
var online = navigator.onLine;
window.addEventListener("offline", function(e) { online = false; });
window.addEventListener("online", function(e) { online = true; });
alert(online);
Edit:
I needed this functionality in a project and realized that my first answer was flawed. Her problem is that different browsers have different understandings of what it is online
and offline
.
I found another solution that is trustworthy. You need to use your server and it is done in 2 different ways depending on you have CORS activated or not.
With active CORS:
function testaLigacao(callback) {
var xhr = new XMLHttpRequest();
var url = "http://teusite.com"; // <--- o teu url aqui
var novoNumero = new Date().getTime();
xhr.open('HEAD', url + "?rand=" + novoNumero, true);
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) return;
if (xhr.status >= 200 && xhr.status < 304) return callback(xhr.responseText, true);
return callback(xhr.responseText, false);
}
try {
xhr.send();
} catch (e) {
return callback(e, false);
}
}
* - this jsFiddle is an example of how to use it, it doesn’t work because it is using a dummy url. You have to use your url
With CORS blocked:
In this case you will need to use JSONP, and have a echo page as JSONP needs it. Javascript is:
function testaLigacao(callback) {
var response;
var callbackName = 'temp_callback_' + new Date().getTime() + Math.floor(Math.random() * 100);
window[callbackName] = function (res) {
delete window[callbackName];
document.body.removeChild(script);
response = res;
};
var src = 'http://teusite.com/ping.php?callback=' + callbackName;
var script = document.createElement('script');
script.src = src;
script.onload = function () {
callback(true);
}
script.onerror = function () {
callback(false);
}
document.body.appendChild(script);
}
* - this jsFiddle is an example of how to use it, it doesn’t work because it is using a dummy url. You have to use your url
More about JSONP here (link).
More about CORS here (link)