Skip to content

Instantly share code, notes, and snippets.

@patrickbrandt
Last active March 16, 2016 17:37
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 patrickbrandt/b7480e50f0d17fe2827f to your computer and use it in GitHub Desktop.
Save patrickbrandt/b7480e50f0d17fe2827f to your computer and use it in GitHub Desktop.
Network connectivity-check worker + angular 1 service wrapper
angular.module('example')
.controller('MainCtrl', ['connectivityService', function(connectivityService) {
connectivityService.onReconnect(function(){
console.log('back online');
});
connectivityService.onLostConnection(function(){
console.log('lost connection');
});
connectivityService.start();
}]);
angular.module('example').factory('connectivityService', ['$window', function($window) {
var _worker;
var _callbacks = {};
return {
start: function(options) {
if (_worker) _worker.terminate();
_worker = new $window.Worker('./connectivityWorker.js');
_worker.onmessage = function(e) {
if (e.data === 'onReconnect' && _callbacks.reconnect) {
_callbacks.reconnect();
}
if (e.data === 'onLostConnection' && _callbacks.lostConnection) {
_callbacks.lostConnection();
}
};
if (options) _worker.postMessage(options);
},
onReconnect: function(cb) {
_callbacks.reconnect = cb;
},
onLostConnection: function(cb) {
_callbacks.lostConnection = cb;
}
};
}]);
//see: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine
//: while you can assume that the browser is offline when it returns a false value,
//you cannot assume that a true value necessarily means that the browser can access the internet
//a good example of connectivity checks using xhr or images: https://github.com/HubSpot/offline/blob/master/js/offline.js
//example: Offline.options = {checks: {xhr: {url: '/connection-test'}}};
var _wasConnected = true;
var _url = 'http://www.apple.com/library/test/success.html';
var _checkInterval = 1000;
var self = this;
function testConnectivity() {
if (navigator.onLine) {
if (!_wasConnected) {
checkUrl(_url).then(function() {
_wasConnected = true;
self.postMessage('onReconnect');
})
.catch(function(){
//console.log('connectivity down');
});
}
} else if (_wasConnected) {
_wasConnected = false;
postMessage('onLostConnection');
}
}
function checkUrl(url) {
return new Promise(function(resolve, reject) {
var onLoad = function(e) {
if (httpRequest.status == 200) {
return resolve();
} else {
return reject(httpRequest.statusText);
}
};
var onError = function(e) {
return reject(e);
};
var httpRequest = new XMLHttpRequest();
httpRequest.onload = onLoad;
httpRequest.onerror = onError;
httpRequest.open('GET', url, true);
httpRequest.send(null);
});
}
setInterval(testConnectivity, _checkInterval);
onmessage = function(options) {
_url = options.data.url;
_checkInterval = options.data.interval;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment