This plugin provides information about device's network.

Step 1 - Install Network Information Plugin

Open command prompt window and run the following code to install this plugin:

C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-network-information
 

Step 2 - Adding Buttons

We will add one button in index.html file that will fetch info about the network.

<button id = "netInfo">INFO</button>
 

Step 3 - Adding Event Listeners

In index.js file, we have to add three event listeners inside onDeviceReady function. The first will act on clicks on the INFO button and the other two will act to the changes in connection status.

document.getElementById("netInfo").addEventListener("click", netInfo);

document.addEventListener("offline", Offlineon, false);
document.addEventListener("online", Onlineon, false);

 

Step 4 - Create Functions

When INFO button is clicked, netInfo() function will return information about current network connection. We are calling type method. The other functions are Offlineon and Onlineon. These functions are working to the network connection changes or any change will display the corresponding alert message.

function netInfo()
 {
   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]);
}
function Offlineon ()
 {
   alert('You are now offline!');
}
function Onlineon ()
 {
   alert('You are now online!');
}

 

When we start the app connected to the network, onOnline function will trigger alert.


Cordova - Network Information


If we press INFO button the alert will show our network state.


Cordova - Network Information


If we disconnect from the network, onOffline function will be called.


Cordova - Network Information

  Modified On Mar-19-2018 03:55:06 AM

Leave Comment