Check connection using cordova plugin


#1

I installed this (https://github.com/apache/cordova-plugin-network-information/blob/master/doc/index.md) in my project

and within my angularjs controller

I pasted this code showed by the doc

function checkConnection() {
    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]);
}

checkConnection(); 

I got an error saying Cannot read property ‘type’ of undefined. Am I missing something?


#2

If you ar running in the browser, the cordova plugin is not loaded and will give an error :wink:

I would also like to notify you of ngCordova, which are angular wrappers for cordova plugins, you can find the network plugin here:

http://ngcordova.com/docs/#Network


#3

Hi @eldy,

You can throw an if(window.Connection) in there to see if it is available. Should prevent errors.

There is also a writeup if you’re still having issues.

Regards,