-
-
Save kcdipesh/053f98c33b32a4227a4b to your computer and use it in GitHub Desktop.
Angularjs service (meant for ionicframework) to detect wether the user is online or not.Works for both web-view and browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var myApp = angular.module('myApp') | |
| .factory('CordovaNetworkAsync', ['$ionicPlatform', '$q', | |
| function($ionicPlatform, $q) { | |
| var Connection = window.Connection || { | |
| "CELL": "cellular", | |
| "CELL_2G": "2g", | |
| "CELL_3G": "3g", | |
| "CELL_4G": "4g", | |
| "ETHERNET": "ethernet", | |
| "NONE": "none", | |
| "UNKNOWN": "unknown", | |
| "WIFI": "wifi" | |
| }; | |
| var asyncGetConnection = function() { | |
| var q = $q.defer(); | |
| $ionicPlatform.ready(function() { | |
| if (navigator.connection) { | |
| q.resolve(navigator.connection); | |
| } else { | |
| //don't worry we can still resolve this one later on! | |
| q.resolve({ | |
| type: 'UNKNOWN' | |
| }); | |
| } | |
| }); | |
| return q.promise; | |
| }; | |
| return { | |
| isOnline: function() { | |
| return asyncGetConnection().then(function(networkConnection) { | |
| var isConnected = false; | |
| switch (networkConnection.type) { | |
| case Connection.ETHERNET: | |
| case Connection.WIFI: | |
| case Connection.CELL_2G: | |
| case Connection.CELL_3G: | |
| case Connection.CELL_4G: | |
| case Connection.CELL: | |
| isConnected = true; | |
| break; | |
| case 'UNKNOWN': | |
| //most browsers already support navigator.onLine | |
| isConnected = navigator.onLine || false; | |
| break; | |
| } | |
| return isConnected; | |
| }); | |
| } | |
| }; | |
| } | |
| ]); | |
| myApp.controller('AppCtrl', function(CordovaNetworkAsync) { | |
| CordovaNetworkAsync.isOnline().then(function(isOnline) { | |
| if (isOnline) { | |
| console.log('you are online'); | |
| } else { | |
| console.log('you are offline'); | |
| } | |
| }).catch(function(err) { | |
| console.log(err); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment