我正在使用navigator.network.connection.type
来获取设备的网络状态。但它显示错误
TypeError: Result of expression 'navigator.network' [undefined] is not an object.
我尝试使用Phonegap 1.0.0,Cordova 1.7.0,Cordova 1.7.0rc1,但我仍然遇到同样的错误。
它适用于iOS但不适用于Android。有人可以帮我这个吗?
这是我的代码:
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
checkConnection();
loaddb();
}
function checkConnection() {
alert(navigator.network);
if(navigator.network==undefined) {
window.localStorage.setItem("internetAccessFlag","false");
} else {
var networkState = navigator.network.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.NONE] = 'No network connection';
if(networkState==Connection.UNKNOWN || networkState==Connection.NONE) {
window.localStorage.setItem("internetAccessFlag","false");
} else {
window.localStorage.setItem("internetAccessFlag","true");
}
//alert(window.localStorage.getItem("internetAccessFlag"));
}
}
</script>
编辑: - 我使用的是Cordova 1.7.0和plugins.xml
<plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager"/>
我有什么关系吗?
答案 0 :(得分:2)
这段代码非常适合我:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script>
<script type="text/javascript" charset="utf-8">
var deviceInfo = function(){
alert(navigator.network.connection.type);
}
function init(){
console.log("GOT AN ONLOAD!!!")
document.addEventListener("deviceready", deviceInfo, true);
}
</script>
</head>
<body onload="init();">
A body...
</body>
</html>
此外,当您从iOS迁移到Android时,您是否使用了Android版的cordova.js?每个平台都有一个平台相关的cordova.js。
答案 1 :(得分:0)
检查您的phonegap版本,然后下载您正在使用的当前版本的PLUGIN。 例如Cordova 3.X:http://docs.phonegap.com/en/3.3.0/cordova_connection_connection.md.html