Cordova 插件在您的 Web 应用程序和移动操作系统的本机 API 之间架起了一座桥梁。为了使用本机端,您必须等到 cordova 准备好。如果您想检查用户是否在线或离线,您可以添加问题中链接的插件,然后像这样使用它:
首先创建一个将返回的函数true
or 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
and 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
插入。阅读文档更多细节。