cordova navigator.connection.type is not working

时间:2016-07-11 23:12:28

标签: javascript cordova

I'm making a hybrid HTML5 applications using cordova. events such as deviceready and backbutton all running correctly. but when the event navigator.connection.type in execution, the event does not work correctly. Here is the code

<head>
   <script type="text/javascript" src="./lib/js/cordova.js"></script>
</head>
<script>
   function onLoad(){
       document.addEventListener("deviceready", onDeviceReady, false);
   }

   function onDeviceReady() {
       document.addEventListener("backbutton", onBackButton, false);
       checkConnection();
   }

   function checkConnection() {
       alert("test");  // first alert. Work

       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';

       alert('Connection type: ' + states[networkState]);  // second alert
   }

   function onBackButton() {
       // code
   }
</script>
<body onload="onLoad()">
    <!-- code -->
</body>

I use two alerts, the first alert works well while the second alert is not working. I've added a plugin cordova plugin add-plugin-network-information to my app using node.js command prompt too. Any help greatly appreciated.

1 个答案:

答案 0 :(得分:0)

你不需要那个onload功能。 它很可能太快调用你的checkConnection函数。

试试这个;

document.addEventListener("deviceready", onDeviceReady, false);


function checkConnection() {
   alert("test");  // first alert. Work

   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';

   alert('Connection type: ' + states[networkState]);  // second alert
 }


function onDeviceReady() {
  checkConnection();
}

Cordova将处理onDeviceReady