Detect phase change, Navigator.online

Asked

Viewed 455 times

11

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

To verify I make a mere

if(navigator.onLine) == conectado 
else == nao conectado

1 answer

9


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

jsFiddle: http://jsfiddle.net/h36no4vh/ *

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

jsfiddle: http://jsfiddle.net/aunrh78o/ *

* - 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.