-1

I am working on an AngularJS app. I am trying to detect if the user is on the internet (vs just a network). In an attempt to do this, I thought I would fire off an $http.get to Google.com. I'm trying this:

myApp.controller('MyController', function($scope, $http) {
  $scope.canConnectToInternet = null;
  $scope.start = function() {
    $http.get('http://www.google.com').then(function(result) {
      console.log(result);
    });
  };
  $scope.start();
});

Unfortunately, this code triggers the dreaded "XMLHttpRequest cannot load http://www.google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. " error. I understand this is a security mechanism. However, as an app developer, I feel there should be a way for me to explicitly bypass it.

How can I make a request to a web site just to detect if I'm on the internet?

Thank you!

xam developer
  • 1,923
  • 5
  • 27
  • 39
  • Just FYI - https://developer.mozilla.org/en-US/docs/Online_and_offline_events – Ian Aug 10 '14 at 14:02
  • this means that the browser WAS indeed able to issue a request, hence your client is online. – Abhinav Gujjar Aug 10 '14 at 14:41
  • @Ian - I couldn't tell if the online/offline events actually detected if you were online, or just hitting a network. Imagine the starbucks scenario where you have to agree to terms before actually getting online. – xam developer Aug 10 '14 at 17:48

1 Answers1

0

You have to change to test against any site that support either JSONP or CORS (that allow any origin of course).

Or if you don't mind, you could use a 3rd party service like Any Origin to enable JSONP support for any url like this:

$scope.status = 'Checking ..';

$http.jsonp('http://anyorigin.com/get?url=www.google.com&callback=JSON_CALLBACK')
  .success(function () {
    $scope.status = 'Online :)';
  })
  .error(function () {
    $scope.status = 'Offline :(';
  });

Example Plunker: http://plnkr.co/edit/htUbrkcf4QaLTsFF1IV2?p=preview

runTarm
  • 11,537
  • 1
  • 37
  • 37