如何在JavaScript中检测Internet连接是否离线?
当前回答
我的方式。
<!-- 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>
其他回答
window.navigator.onLine
是你要找的,但这里要添加的东西很少,首先,如果它是你想要持续检查的应用程序上的一些东西(比如看看用户是否突然脱机,在这种情况下大多数时候是正确的,那么你也需要监听变化),为此你添加事件监听器到窗口来检测任何变化,为了检查用户是否脱机,你可以这样做:
window.addEventListener("offline",
()=> console.log("No Internet")
);
检查是否在线:
window.addEventListener("online",
()=> console.log("Connected Internet")
);
几乎所有主流浏览器现在都支持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年的更新已经不是他的了。
我正在寻找一种客户端解决方案,以检测互联网是否宕机或服务器是否宕机。我发现的其他解决方案似乎总是依赖于第三方脚本文件或图像,这对我来说似乎不像是经得起时间的考验。将来可能会更改外部托管脚本或映像,从而导致检测代码失败。
我找到了一种方法,通过查找带有404代码的xhrStatus来检测它。此外,我使用JSONP绕过CORS限制。如果状态码不是404,则表明网络连接无法工作。
$.ajax({
url: 'https://www.bing.com/aJyfYidjSlA' + new Date().getTime() + '.html',
dataType: 'jsonp',
timeout: 5000,
error: function(xhr) {
if (xhr.status == 404) {
//internet connection working
}
else {
//internet is down (xhr.status == 0)
}
}
});
IE 8将支持window.navigator.onLine属性。
但当然,这对其他浏览器或操作系统没有帮助。考虑到了解Ajax应用程序中的在线/离线状态的重要性,我预计其他浏览器供应商也将决定提供该属性。
在此之前,XHR或Image()或<img>请求都可以提供接近您想要的功能。
更新(2014/11/16)
大多数浏览器现在都支持这个属性,但结果会有所不同。
引用自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. All other conditions return a true value.
只需使用导航器。如果这是真的,那么你是在线的,否则离线
推荐文章
- 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 ?