Using navigator.onLine
You can use navigator.onLine and transfer it to a helper variable, e.g. ( 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 view it in the controller:
$scope.$watch('online', function(newStatus) { ... });
But that just serves as a dirty check to find out if the computer is really connected to the network, and does not mean that the Internet is working.
Using fake AJAX request
You can make fun of a service that executes a fake request in a browser ( warning: untested 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 {...} }); });
The code for the request is laughing at this link .
Also note that this will not work with localhost , because the server will work even when disconnected from the Internet.
source share