如何在JavaScript中检测Internet连接是否离线?
当前回答
我不得不为一个与学校有很多合作的客户制作一个web应用程序(基于ajax),这些学校的互联网连接经常不好,我使用这个简单的功能来检测是否有连接,工作得非常好!
我使用CodeIgniter和Jquery:
function checkOnline() {
setTimeout("doOnlineCheck()", 20000);
}
function doOnlineCheck() {
//if the server can be reached it returns 1, other wise it times out
var submitURL = $("#base_path").val() + "index.php/menu/online";
$.ajax({
url : submitURL,
type : "post",
dataType : "msg",
timeout : 5000,
success : function(msg) {
if(msg==1) {
$("#online").addClass("online");
$("#online").removeClass("offline");
} else {
$("#online").addClass("offline");
$("#online").removeClass("online");
}
checkOnline();
},
error : function() {
$("#online").addClass("offline");
$("#online").removeClass("online");
checkOnline();
}
});
}
其他回答
我的方式。
<!-- the file named "tt.jpg" should exist in the same directory -->
<script>
function testConnection(callBack)
{
document.getElementsByTagName('body')[0].innerHTML +=
'<img id="testImage" style="display: none;" ' +
'src="tt.jpg?' + Math.random() + '" ' +
'onerror="testConnectionCallback(false);" ' +
'onload="testConnectionCallback(true);">';
testConnectionCallback = function(result){
callBack(result);
var element = document.getElementById('testImage');
element.parentNode.removeChild(element);
}
}
</script>
<!-- usage example -->
<script>
function myCallBack(result)
{
alert(result);
}
</script>
<a href=# onclick=testConnection(myCallBack);>Am I online?</a>
正如olliej所说,使用导航器。在线浏览器属性比发送网络请求更可取,因此developer.mozilla.org/En/Online_and_offline_events甚至被旧版本的Firefox和IE支持。
最近,WHATWG已经指定了在线和离线事件的添加,以防您需要在导航器上进行反应。在线更改。
请注意Daniel Silveira发布的链接,他指出依赖这些信号/属性与服务器同步并不总是一个好主意。
对域的ajax调用是检测您是否脱机的最简单方法
$.ajax({
type: "HEAD",
url: document.location.pathname + "?param=" + new Date(),
error: function() { return false; },
success: function() { return true; }
});
这只是给大家一个概念,还需要改进。
例如,error=404仍然意味着您在线
几乎所有主流浏览器现在都支持window.navigator. online属性,以及相应的在线和离线窗口事件。运行以下代码片段来测试它:
console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line'); window.addEventListener('online', () => console.log('Became online')); window.addEventListener('offline', () => console.log('Became offline')); document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine)); <button id="statusCheck">Click to check the <tt>window.navigator.onLine</tt> property</button><br /><br /> Check the console below for results:
尝试将您的系统或浏览器设置为离线/在线模式,并检查日志或window.navigator.onLine属性的值变化。
请注意Mozilla文档中的这段话:
In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking. In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. Until Firefox 41, all other conditions return a true value; since Firefox 41, on OS X and Windows, the value will follow the actual network connectivity.
(重点是我自己的)
这意味着如果window.navigator.onLine为false(或者您得到一个脱机事件),则保证您没有Internet连接。
然而,如果它是真的(或者你得到一个在线事件),它充其量只意味着系统连接到某个网络。这并不意味着你可以上网。要检查这一点,您仍然需要使用其他答案中描述的解决方案之一。
我最初打算把这篇文章作为格兰特·瓦格纳(Grant Wagner)的回答的更新,但这似乎太过编辑了,尤其是考虑到2014年的更新已经不是他的了。
您可以使用$.ajax()的错误回调,它在请求失败时触发。如果textStatus等于字符串"timeout",这可能意味着连接中断:
function (XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown
// will have info
this; // the options for this ajax request
}
医生说:
错误:一个函数被调用,如果请求 失败。函数被传递了3个 参数:XMLHttpRequest对象 描述错误类型的字符串 这是可选的 异常对象,如果发生。 第二个可能的值 参数(除null外)为"timeout", "error", "notmodified"和 “parsererror”。这是一个Ajax事件
例如:
$.ajax({
type: "GET",
url: "keepalive.php",
success: function(msg){
alert("Connection active!")
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if(textStatus == 'timeout') {
alert('Connection seems dead!');
}
}
});
推荐文章
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 用jQuery检查Internet连接是否存在?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?