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

痞子三分冷 提交于 2019-12-06 15:55:08

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]);
}

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