Jan Van Echelpoel
Jan Van Echelpoel

Reputation: 53

PhoneGap offline event fires too slow

In my PhoneGap app I first check if the device is connected to the internet before running code and calling an API etc.

if (window.navigator.onLine == false) {
    //error handling
} else {
    //do stuff & call API
}

This perfectly works, but if the device loses it's connection and the page is reloaded WITHIN 5 seconds or so after I diconnected, the code still fires and the API is called although the device is not connected anymore. If the page is reloaded AFTER approximately 5 seconds the error handling is fired as expected.

So it looks like it takes up to approximately 5 seconds after the connection is lost to change to "offline". I double checked this with the offline event and it was only fired after those 5 seconds.

document.addEventListener("offline", onOffline, false);

function onOffline() {
    alert("now offline");
}

So is there a way to check immediately when the connection is lost or being deactived or something?

Upvotes: 2

Views: 366

Answers (1)

Dawson Loudon
Dawson Loudon

Reputation: 6029

If the issue is specifically with checking online status directly at page load, use the network-information plugin and call a function directly after page load completes:

function checkConnection() {
    var networkState = navigator.network.connection.type;
    var states = {};
    states[Connection.UNKNOWN]  = false;
    states[Connection.ETHERNET] = true;
    states[Connection.WIFI]     = true;
    states[Connection.CELL_2G]  = true;
    states[Connection.CELL_3G]  = true;
    states[Connection.CELL_4G]  = true;
    states[Connection.NONE]     = false;
    return states[networkState];
}

The offline and online events work specifically once the application is in use. The network-information plugin can return connection status as soon as the deviceready event is fired.

Upvotes: 3

Related Questions