通过我的 Web 应用程序,检测我的移动设备是否有互联网连接的最佳方法是什么?
通过我的 Web 应用程序,检测我的移动设备是否有互联网连接的最佳方法是什么?
不需要编写代码,这是HTML5 API的一部分。检查window.navigator.onLine
的值 - 如果用户离线,则该值将为false
。
http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#browser-state
timeout
,然后添加一个 error
处理程序,查找 textStatus
(第二个参数)为 'timeout'
。$.ajaxSetup({
timeout: 1, // Microseconds, for the laughs. Guaranteed timeout.
error: function(request, status, maybe_an_exception_object) {
if(status != 'timeout')
alert("YOU BROKE IT");
else
alert("OH NOES TEH INTARWEBS ARE DOWN!!!!!1one");
}
});
在简单的JS代码中,这可以完成,因为所有特色设备都不支持JS。然而,对于基于Web的应用程序来说,这是使用最少代码的方法。
online = window.navigator.onLine;
if (navigator.onLine) {
alert('you are online');
} else {
alert('you are offline');
}
如果您想每隔X秒检查连接。
$(document).ready(function() {
setInterval(function(){
var isOnline = navigator.onLine;
if (isOnline) {
console.log("Connected");
}
else {
console.log("Not Connected");
}
}, 30000); // 10000 = 10 seconds, check for connection every 30 seconds
});