检查设备是否有Internet访问权限的最佳方法是什么? [英] What is the best way to check if the device has Internet access?
问题描述
我想检查设备是否具有互联网访问。从官方cordova文档:
I want to check if the device has internet access. From the official cordova documentation:
这段代码只是获取连接类型
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();
但是如何检查设备是否真的可以上网?也就是说,因为可能是设备使用WiFi连接类型连接到路由器,但是它不能访问互联网而只能访问本地访问。在这种情况下, checkConnection();
将返回: WiFi连接
。
But how can I check if the device really have internet access? That is, because it may be that the device is connected to a router using a WiFi connection type, but that it has no access to internet but only local access. In this case the checkConnection();
will return: WiFi connection
.
或者是连接到3G网络电话运营商,但用户没有足够的信用额度用于互联网。在这种情况下, checkConnection();
将返回: Cell 3G连接
Or that is connected to a 3G network phone operator, but the user does not have sufficient credits for the internet. In this case the checkConnection();
will return: Cell 3G connection
但是在这两种情况下,用户都没有真正的互联网访问事件,如果连接。
But in both cases the user have not a real internet access eventhough if connected.
我认为唯一的事情是ping google或其他服务器在州[networkState]!=没有网络连接
The only thing that I think is to ping google or another server to check if there really has internet access, in the case of states[networkState] != No network connection
的情况下检查是否真的有互联网连接你认为 navigator.onLine
可以在所有设备(Android,iOS,BlackBery 10?)上运行吗?
Or do you think navigator.onLine
can run on all devices (Android, iOS, BlackBery 10?
推荐答案
这里是一个讨论 http://iswwwup.com/t/f3e5374b74ca/android-cordova-plugin-to -detect-internet-connection.html
他们提到的解决方案...
And the solution they mentioned...
测试此地址以检查设备是否可以访问互联网的功能如下:
A function to test this address to check if the device has access to internet would look like this :
function testInternet(win,fail){
$.get("http://www.google.fr/blank.html").done(win).fail(fail);
}
Or ,
function testInternet(win,fail){
$.ajax({
url:"http://www.google.fr/blank.html",
timeout:5000, //timeout to 5s
type: "GET",
cache: false
}).done(win).fail(fail);
}
这篇关于检查设备是否有Internet访问权限的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!