Cordova 插件在您的网络应用程序和移动操作系统的本机 API 之间架起了一座桥梁。为了使用本地端,你必须等到科尔多瓦准备好。如果您想检查用户是在线还是离线,您可以添加问题中链接的插件,然后像这样使用它:
首先创建一个函数,根据用户是否在线返回true 或false:
function checkConnection(){
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';
if(states[networkState].indexOf("WiFi") != -1 || states[networkState].indexOf("Cell") != -1)
return true;
return false;
}
当您获得设备就绪事件时:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// Now safe to use device APIs
var connected = checkConnection();//will return true or false
if(connected){
//user is online
}else{
//user is offline
}
}
您也可以像这样直接监听online 和offline 事件:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// Now safe to use device APIs
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
}
function onOnline() {
// User is Online
}
function onOffline() {
// User is Offline
}
这两种方法都需要添加network-information 插件。阅读documentation了解更多详情。