Cannot read the property 'type' of undefined error in cordova network plugin

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

I am developing android application using cordova and ionic framework,using network plugin from here (https://github.com/apache/cordova-plugin-network-information). But the device ready alert fires off and then I get the the following error.

"TypeError: Cannot read property 'type' of undefined 

Here is navigator object

navigator.connection.type  

I will get error in following line.

回答1:

use mine

document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready function onDeviceReady() {     checkConnection() }  function checkConnection() {     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]); } 


回答2:

For some reason, the navigator.connection object is not ready at the same time as cordova is.

You have to use a timeout, such as this one - designed for Angular/Ionic

   setTimeout(function(){         var connection = connectionService.getConnection();         console.log("connection : "+connection);         $scope.connection = connection;         $scope.$apply()     }, 5000) 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!