navigator.onLine on Ionic app

2019-07-25 11:07发布

In my Ionic app, I need to perform certain actions based on whether user is offline or online.

I would be using $cordovaNetwork plugin in the app to find the connectivity status. However, during development on my laptop I am looking for an easy way to test the connectivity (without having to deploy on the device).

So, I thought of using navigator.onLine to test offline/online business logic. But even if I switch off wifi on the laptop (there is no LAN cable plugged to the laptop), navigator.onLine still returns true.

Can someone please advice how can I make navigator.onLine return false or any other way to find out whether there is internet connection or not?

EDIT: Browser is Chrome

1条回答
淡お忘
2楼-- · 2019-07-25 11:44

The service code:

//service to check if device or (browser) is online or offline

.factory('ConnectivityMonitor', function($rootScope, $cordovaNetwork){

  return {
    isOnline: function(){
      if(ionic.Platform.isWebView()){
        return $cordovaNetwork.isOnline(); 
      } else {
        return navigator.onLine;
      }
    },
    isOffline: function(){
      if(ionic.Platform.isWebView()){
        return !$cordovaNetwork.isOnline();    
      } else {
        return !navigator.onLine;
      }
    },
startWatching: function(){
    if(ionic.Platform.isWebView()){

      $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
        console.log("went online");
      });

      $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
        console.log("went offline");
      });

    }else {

      window.addEventListener("online", function(e) {
        console.log("went online");
      }, false);    

      window.addEventListener("offline", function(e) {
        console.log("went offline");
      }, false);  
    }       
}
  }
})

Then in controller (an example):

.controller('Map3Ctrl',   
function(ConnectivityMonitor) {

 if(ConnectivityMonitor.isOnline()){
    console.log("online")
 }else{
  console.log("offline");
 }

})

Monitoring Online and Offline States in an Ionic Application

查看更多
登录 后发表回答