【发布时间】:2016-03-14 22:05:11
【问题描述】:
通过我的网络应用程序检测我的手机是否有互联网连接的最佳方法是什么?
【问题讨论】:
标签: javascript html jquery-mobile internet-connection
通过我的网络应用程序检测我的手机是否有互联网连接的最佳方法是什么?
【问题讨论】:
标签: javascript html jquery-mobile internet-connection
这不需要任何代码——它是 HTML5 API 的一部分。检查window.navigator.onLine 的值——如果用户离线,它将是false。
http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#browser-state
【讨论】:
<body onload='updateIndicator()' ononline='updateIndicator()' onoffline='updateIndicator()'> <!--Check internet Connection --> <script><br/> function updateIndicator() { document.getElementById('indicator').textContent = navigator.onLine ? 'online' : 'offline'; } </script> <p>The network is: <span id="indicator">(state unknown)</span> </body>我尝试格式化但不能:(
一个选项可能是changing the Ajax settings 来添加特定的timeout,然后添加一个error 处理程序来查找textStatus(第二个参数)'timeout'。
发生超时时,互联网连接不稳定或您的网站已关闭。
使用ajaxSetup 为所有请求设置选项默认值:
$.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
});
【讨论】:
如果你想要比 window.navigator.onLine 更具兼容性、可靠性和可定制性的东西,试试我的 jQuery 插件:http://tomriley.net/blog/archives/111
【讨论】: