Using navigator.onLine
You can use navigator.onLine
and wrap it on a helper variable, like this (Credits to this answer)
myApp.run(function($window, $rootScope) {
$rootScope.online = navigator.onLine;
$window.addEventListener("offline", function () {
$rootScope.$apply(function() {
$rootScope.online = false;
});
}, false);
$window.addEventListener("online", function () {
$rootScope.$apply(function() {
$rootScope.online = true;
});
}, false);
});
and then watch it in the controller:
$scope.$watch('online', function(newStatus) { ... });
But that just serves as a dirty check to know if the PC is actually connected to a network, not meaning that the internet is working.
Using a fake AJAX request
You can mock a service that does a fake request to a browser (warning: non-tested code below)
myApp.service('Internet', function($http){
this.IsOk = function () {
return $http({ method: 'HEAD', url: '/' + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000) })
.then(function(response) {
var status = response.status;
return status >= 200 && status < 300 || status === 304;
});
}
});
And then use something in this context:
myApp.controller('TestController', function(Internet){
Internet.IsOn().then(function(isok){
if(isok) {...} else {...}
});
});
Code for request mocking in this link.
Also note that it will not work using localhost
, because the server will work even when disconnected to the internet.