May 21, 2021 Cordova
This plug-in provides information about the device network.
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
Let'.html a button in index to get information about the network.
<button id = "networkInfo">INFO</button>
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);
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.
If we press the INFO button, the alert will show our network status.
If we disconnect from the network, the onOffline function is called.