要安裝這個外掛,我們將開啟命令提示字元,然後執行下面的程式碼 ?
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-network-information
<button id = "networkInfo">INFO</button>
我們將在index.js 的 onDeviceReady函式內部新增三個事件偵聽器。一個用於監聽我們之前建立的按鈕點選,另外兩個將監聽連線狀態的變化。
document.getElementById("networkInfo").addEventListener("click", networkInfo); document.addEventListener("offline", onOffline, false); document.addEventListener("online", onOnline, false);
當按鈕被點選 networkInfo 函式將返回有關當前網路連線的資訊。我們呼叫 type 方法。其他函式是 onOffline 和 onOnline。這些函式正在偵聽連線變化,任何變化都會觸發相應提示訊息。
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!'); }