Detect phase change, navigator.online

10

I use this navigator.onLine to check if the user is logged in, however I need to constantly check and use setInterval for this, is there a more elegant way that leaves this gambiarra back type on('navigator.online') ?

To check I do a merge

if(navigator.onLine) == conectado 
else == nao conectado
    
asked by anonymous 29.05.2015 / 22:12

1 answer

8

According to MDN there are both online and offline events %, so you can detect changes instantly and know the status whenever you need it without needing 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 response has flaws. The problem with it is that different browsers have different understandings of what is online and offline .

I found another solution that you can trust. You need to use your server and do it in 2 different ways depending on whether or not you have CORS enabled or not.

With CORS active:

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

jsFiddle: link *

* - this jsFiddle is an example of how to use it, it does not work because you are using a dummy url. You have to use your url

With CORS blocked:

In this case you will have to use JSONP, and have a page that echo as JSONP needs. The 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);
}

jsfiddle: link *

* - this jsFiddle is an example of how to use it, it does not work because you are using a dummy url. You have to use your url

More about JSONP here (link) . More about CORS here (link)

    
29.05.2015 / 22:18