SwatchDog
SwatchDog

Reputation: 61

How to catch flaky Internet connections

I have a situation where the user has a Wi-Fi connection, but the Wi-Fi is not connected to the Internet.

So navigator.onLine produces a true, but in reality the user is not online. Short of doing an actual ajax call, is there another indicator to tell whether we’re online or not?

I seem to remember that PhoneGap had an extra indicator.

Upvotes: 5

Views: 217

Answers (3)

Havenard
Havenard

Reputation: 27864

Only reliable way really is to try to reach something out there. It can be done hitting against some file of your own site.

i_am_online = true;

function connectivity_test()
{
    if (navigator.onLine) // have network, test if can actually reach the server
    {
        $.ajax('/some_static_file.html', { type: 'HEAD', cache: false })
        .done(function() { setTimeout(connectivity_test, 2000); i_am_online = true; })
        .fail(function() { setTimeout(connectivity_test, 2000); i_am_online = false; });
    }
    else // without network I'm offline, no need to ping
    {
        setTimeout(connectivity_test, 2000);
        i_am_online = false;
    }
}

connectivity_test();

This should test for peer connectivity every 2 seconds and update the variable i_am_online with true or false accordingly.

Test against some static file to make sure you won't trigger server-side scripts. The method HEAD will cause only the headers to be sent, so this "ping" will generate minimal network traffic regardless of the file size.

Upvotes: 4

user123_456
user123_456

Reputation: 5805

Something like this should work

var req = new XMLHttpRequest();
req.open('GET', 'http://www.google.com', false);
req.send(null);
if(req.status == 200)
   alert(req.responseText);

Upvotes: 3

Phillip Senn
Phillip Senn

Reputation: 47605

window.addEventListener("online", NowOnline, false);
window.addEventListener("offline", NowOffline, false);

Upvotes: 2

Related Questions