我尝试了一些建议,例如navigator.onLine,但即使是在飞行模式下,我的应用程序“认为”它在线。
我也找到了一些关于AJAX的建议,但我只想检查是否在线以打开外部网页。 如果没有连接,我打算显示消息,例如“您的设备似乎处于离线状态。 请检查您的连接!”。
我尝试了一些建议,例如navigator.onLine,但即使是在飞行模式下,我的应用程序“认为”它在线。
我也找到了一些关于AJAX的建议,但我只想检查是否在线以打开外部网页。 如果没有连接,我打算显示消息,例如“您的设备似乎处于离线状态。 请检查您的连接!”。
cordova网络信息插件
,它可以为您无缝完成此工作。该插件提供设备的蜂窝移动数据和Wi-Fi连接信息,并确定设备是否联网。下载插件:https://www.npmjs.com/package/cordova-plugin-network-information
试一下吧。
document.addEventListener("deviceready", function(e){
console.log(navigator.connection.type);
document.addEventListener("offline", function(e){
alert("NO_NETWORK");
}, false);
}, false);
离线
当应用程序离线时,设备未连接到互联网时触发此事件。
document.addEventListener("offline", yourCallbackFunction, false);
你可以使用这个插件
然后,你可以在你的应用程序中任何地方使用它,无需导入它。
if(navigator.connection.type === 'none') {
alert('there is no internet')
}
您可以将其添加到setInterval中,以每5秒检查一次互联网连接。
setInterval(() => {
if(navigator.connection.type === 'none') {
alert('there is no internet')
} }, 5000);
还有其他与"navigator.connection.type"相关的值,例如当存在互联网连接时,"navigator.connection.type"的值是连接类型(如Wi-Fi、4G、3G、Windows上的以太网等)。
通过这个插件
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';
alert('Connection type: ' + states[networkState]);
}
checkConnection();
您可以使用cordova-plugin-network-information
插件检查您的Android设备与互联网的连接性。此外,如果您想在有互联网的情况下执行某些任务,请参见以下内容:
if (navigator.connection.type == "none") {
alert("No Internet Connection...");
}
else {
yourdesiredFunction();
}