我正在尝试确定应用启动时设备是否已连接到互联网。 据我所知,javascript代码应该是这样的:
function isOnline() {
var networkState = navigator.network.connection.type;
if (networkState == Connection.NONE) {
return false;
};
return true;
}
到目前为止,我只在iOS上尝试过它。 不幸的是,navigator.net工作未定义。
我知道我必须在config.xml文件中添加网络模块。 根据PhoneGap页面(http://docs.phonegap.com/en/3.0.0/cordova_connection_connection.md.html), 这就是我做的方式:
<feature name="NetworkStatus">
<param name="ios-package" value="CDVConnection" />
</feature>
<feature name="NetworkStatus">
<param name="android-package" value="org.apache.cordova.NetworkManager" />
</feature>
有人知道我错过了什么吗?
答案 0 :(得分:2)
尝试这个。
在此安装此cordova插件。
https://github.com/apache/cordova-plugin-network-information
并将此代码添加到js文件
中document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
isOnline();
}
function isOnline() {
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]) == states[Connection.NONE]) {
alert('No Internet Connection. Click OK to exit app');
navigator.app.exitApp();
}
}
答案 1 :(得分:0)
试试这个:
function checkConnection() {
return navigator.connection.type === "none" || navigator.network.connection.type === null ||
navigator.connection.type === "unknown" ? false : true;
}
请记得检查此AFTER设备就绪事件已被解雇。