Alert box when no internet connection - Phonegap

后端 未结 9 2678
南方客
南方客 2021-02-20 06:55

I\'m trying to get a pop-up to, well, pop up when there is no internet connection on the device.

I got the following example working, but now I want the alert only to sh

相关标签:
9条回答
  • 2021-02-20 07:42

    I'm just amalgamating a couple of answers here, but I wanted something which responded to the online/offline events but also knew at the start whether there was an internet connection. I was using this in an Angular controller which broadcast about state changes, but I've removed those parts for simplicity.

    document.addEventListener("deviceready", onDeviceReady, false);
    
    function onDeviceReady() {
        var _curStatus = false;
    
        function toggleStatus(newVal) {
            console.log('Setting internet connection state to: ' + newVal);
            _curStatus = newVal;
            // My angular $broadcast went here
        }
    
        var conType = navigator.network.connection.type;
        toggleStatus((conType != Connection.NONE) && (conType != Connection.UNKNOWN));
        document.addEventListener("online", function() {toggleStatus(true);}, false);
        document.addEventListener("offline", function() {toggleStatus(false);}, false);
        }
    }
    
    0 讨论(0)
  • 2021-02-20 07:47

    if you do

    if (states[Connection.NONE]){
       alert('Geen internet :(');
       };
    

    this would happen.
    do this.

    networkState = navigator.network.connection.type
    alert(states[networkState]);
    

    see if this works for u or not.

    EDIT: just compare:

    if (networkState == Connection.NONE){
      alert('no internet ');
    };
    
    0 讨论(0)
  • 2021-02-20 07:48

    Solution :

    <script type="text/javascript" charset="utf-8">
    
    // Wait for PhoneGap to load
    // 
    document.addEventListener("deviceready", onDeviceReady, false);
    
    // PhoneGap is loaded and it is now safe to make calls PhoneGap methods
    //
    function onDeviceReady() {
        checkConnection();
    }
    
    function checkConnection() {
        var networkState = navigator.network.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.NONE]     = 'No network connection';
    
        alert('Connection type: ' + states[networkState]);
    }
    
    </script>
    
    0 讨论(0)
提交回复
热议问题