navigator.onLine not working cordova 5.0.0

后端 未结 2 600
感情败类
感情败类 2021-01-15 02:12

I am having problems with checking if a device has no internet connection. I am using cordova 5.0.0 CLI. This is my code:

if(navigator.onLine) {
  alert(\"on         


        
相关标签:
2条回答
  • 2021-01-15 02:50

    Cordova plugins create a bridge between your web app and the native apis of the mobile OS. In order to use the native side you have to wait until cordova is ready. If you want to check whether the user is online or offline you can add the plugin linked in your question and then use it like this:

    First create a function that will return true or false depending if the user is online or not:

    function checkConnection(){
       var networkState = navigator.connection.type;
    
       var states = {};
       states[Connection.UNKNOWN]  = 'Unknown connection';
       states[Connection.ETHERNET] = 'Ethernet connection';
       states[Connection.WIFI]     = 'WiFi connection';
       states[Connection.CELL_2G]  = 'Cell 2G connection';
       states[Connection.CELL_3G]  = 'Cell 3G connection';
       states[Connection.CELL_4G]  = 'Cell 4G connection';
       states[Connection.CELL]     = 'Cell generic connection';
       states[Connection.NONE]     = 'No network connection';
    
       if(states[networkState].indexOf("WiFi") != -1 || states[networkState].indexOf("Cell") != -1)
            return true;
      return false;
    }
    

    When you get the device ready event:

    document.addEventListener("deviceready", onDeviceReady, false);
    
    function onDeviceReady() {
       // Now safe to use device APIs
       var connected = checkConnection();//will return true or false
    
       if(connected){
          //user is online
       }else{
          //user is offline
       }
    }
    

    Also you can listen directly for online and offline events like this:

    document.addEventListener("deviceready", onDeviceReady, false);
    
    function onDeviceReady() {
    // Now safe to use device APIs
      document.addEventListener("online", onOnline, false);
      document.addEventListener("offline", onOffline, false);
    }
    
    function onOnline() {
       // User is Online
    }
    function onOffline() {
       // User is Offline
    }
    

    Both approaches requires to add the network-information plugin. Read the documentation for more details.

    0 讨论(0)
  • 2021-01-15 02:55

    Add this to your index.html :

    document.addEventListener("offline", function(){ navigator.notification.alert("No connection found") }, false);
    

    It will alert you if there isn't a network connection.

    If you don't have the notification plugin :

    document.addEventListener("offline", function(){ alert("No connection found") }, false);
    
    0 讨论(0)
提交回复
热议问题