Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Cordova network information

May 21, 2021 Cordova

Table of contents

This plug-in provides information about the device network.

Step 1 - Install the network information plug-in

To install this plug-in, we'll open the command prompt and run the following code -

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

Step 2 - Add a button

Let'.html a button in index to get information about the network.

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

Step 3 - Add an event listener

We'.js three event listeners to the onDeviceReady function in index data. /b10> One will listen for clicks on the button we created earlier, and the other two will listen for changes to the connection status.

document.getElementById("networkInfo").addEventListener("click", networkInfo);
document.addEventListener("offline", onOffline, false);
document.addEventListener("online", onOnline, false);

Step 4 - Create a function

The networkInfo function will return information about the current network connection once the button is clicked. /b10> We are calling the type method. /b11> Other features are onOffline and onOnline. /b12> These features are listening for connection changes, and any changes will trigger the appropriate 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 onOffline() {
   alert('You are now offline!');

function onOnline() {
   alert('You are now online!');

When we launch an application connected to the network, the Online feature triggers an alert.

Cordova network information

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

Cordova network information

If we disconnect from the network, the onOffline function is called.

Cordova network information