English 中文(简体)
Cordova - Network Information
  • 时间:2024-10-18

Cordova - Network Information


Previous Page Next Page  

This plugin provides information about device s network.

Step 1 - Instalpng Network Information Plugin

To install this plugin, we will open command prompt and run the following code −

C:UsersusernameDesktopCordovaProject>cordova plugin 
   add cordova-plugin-network-information

Step 2 - Add Buttons

Let s create one button in index.html that will be used for getting info about network.

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

Step 3 - Add Event Listeners

We will add three event psteners inside onDeviceReady function in index.js. One will psten for cpcks on the button we created before and the other two will psten for changes in connection status.

document.getElementById("networkInfo").addEventListener("cpck", networkInfo);
document.addEventListener("offpne", onOffpne, false);
document.addEventListener("onpne", onOnpne, false);

Step 4 - Creating Functions

networkInfo function will return info about current network connection once button is cpcked. We are calpng type method. The other functions are onOffpne and onOnpne. These functions are pstening to the connection changes and any change will trigger the corresponding alert message.

function networkInfo() {
   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 onOffpne() {
   alert( You are now offpne! );
}

function onOnpne() {
   alert( You are now onpne! );
}

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

Cordova Network Onpne

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

Cordova Network Info

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

Cordova Network Offpne Advertisements