Skip to content

Instantly share code, notes, and snippets.

@codyromano
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codyromano/0073bc57fac94343dc09 to your computer and use it in GitHub Desktop.
Save codyromano/0073bc57fac94343dc09 to your computer and use it in GitHub Desktop.
var Network = {
// Host we use for determining connectivity
pingHost: 'http://www.archmi.com',
pingInProgress: false,
// If it's PhoneGap or web app environment
isPhoneGapEnv: network && 'isReachable' in network,
// These default values should not be edited, but they may
// change at runtime
callbacks: {
success: null,
fail: null
},
// Just a general utility. Executes a function only if it exists
callIfDefined: function (fn) {
if (typeof fn === 'function') {
fn();
}
},
// Interpret PhoneGap's network response
checkPGNetworkResp: function (reachability) {
var networkState = reachability.code || reachability;
var successCodes = [NetworkStatus.REACHABLE_VIA_CARRIER_DATA_NETWORK,
NetworkStatus.REACHABLE_VIA_WIFI_NETWORK];
if (successCodes.indexOf(networkState) > -1) {
this.callIfDefined(this.callbacks.success);
} else {
this.callIfDefined(this.callbacks.fail);
}
},
runPingTest: function (tries) {
var _self = this;
var tries = tries || 5;
var currentTry = 0;
// Don't allow simultaneous pings
if (this.pingInProgress === true) {
return false;
}
this.pingInProgress = true;
(function ping() {
// Create an image to use as a test
var img = new Image();
img.src = _self.pingHost;
img.onload = function() {
_self.callIfDefined(_self.callbacks.success);
};
img.onerror = function() {
if (++currentTry < tries) {
setTimeout(ping, 100);
} else {
_self.callIfDefined(_self.callbacks.fail);
}
};
})()
},
getOnlineStatus: function (onSuccess, onFail) {
this.callbacks.success = onSuccess;
this.callbacks.fail = onFail;
if (this.isPhoneGapEnv) {
network.isReachable(this.pingHost, this.checkPGNetworkResp);
} else {
this.runPingTest(5);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment