Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phonegap/Cordova - TypeError: Result of expression 'navigator.network' [undefined] is not an object

I am using navigator.network.connection.type to get the network status of the device. But it shows the error

TypeError: Result of expression 'navigator.network' [undefined] is not an object.

I tried with Phonegap 1.0.0, Cordova 1.7.0, Cordova 1.7.0rc1, but I still get the same error.

It works fine on iOS but not on Android. Can someone help me with this?

Here is my code:

<script type="text/javascript" charset="utf-8">
    document.addEventListener("deviceready",onDeviceReady,false);

    function onDeviceReady() {
        checkConnection();
        loaddb();
    }
    function checkConnection() {
        alert(navigator.network);
        if(navigator.network==undefined) {
            window.localStorage.setItem("internetAccessFlag","false");
        } else {
            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';

            if(networkState==Connection.UNKNOWN || networkState==Connection.NONE) {
                window.localStorage.setItem("internetAccessFlag","false");
            } else {
                window.localStorage.setItem("internetAccessFlag","true");   
            }
            //alert(window.localStorage.getItem("internetAccessFlag"));
        }
    }
</script>

EDIT:- I am using Cordova 1.7.0 and plugins.xml has

<plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager"/>

Is there anything I have to do with this?

like image 780
ilight Avatar asked Nov 03 '22 22:11

ilight


1 Answers

This is code that works perfectly well for me:

<!DOCTYPE HTML>
<html>
  <head>
      <script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script>
      <script type="text/javascript" charset="utf-8">

    var deviceInfo = function(){
      alert(navigator.network.connection.type);
    }

    function init(){
        console.log("GOT AN ONLOAD!!!")
        document.addEventListener("deviceready", deviceInfo, true);
    }
  </script>
  </head>
  <body onload="init();">
      A body...
  </body>
</html>

Also, when you moved from iOS to Android did you use the Android version of cordova.js? There is a platform dependent cordova.js for each platform.

like image 133
Simon MacDonald Avatar answered Nov 15 '22 15:11

Simon MacDonald