如何在JavaScript中检测Internet连接是否离线?
当前回答
if(navigator.onLine){
alert('online');
} else {
alert('offline');
}
其他回答
只需使用导航器。如果这是真的,那么你是在线的,否则离线
我的方式。
<!-- 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>
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.
HTML5应用程序缓存API指定导航器。onLine,目前在IE8测试版中可用,WebKit(例如。Safari)的夜间运行,并且已经在Firefox 3中得到支持
下面是我拥有的一个辅助实用程序片段。这是带名称空间的javascript:
network: function() {
var state = navigator.onLine ? "online" : "offline";
return state;
}
你应该使用这个方法检测,否则发射一个'替代'的方式来做这件事。这将是我们所需要的全部。其他的方法是hack。
推荐文章
- jQuery中的live()转换为on()
- 如何区分鼠标的“点击”和“拖动”
- IE9是否支持console.log,它是一个真实的功能吗?
- Node.js同步执行系统命令
- 如何转义JSON字符串包含换行字符使用JavaScript?
- jQuery等价于JavaScript的addEventListener方法
- jQuery需要避免的陷阱
- JavaScript中变量字符串的XML解析
- 'React'指的是一个UMD全局,但当前文件是一个模块
- 为什么useState不触发重新渲染?
- 如何使用回调与useState挂钩在反应
- 网络请求失败
- 如何使用JavaScript大写字符串中每个单词的第一个字母?
- 如何使用箭头函数(公共类字段)作为类方法?
- 使用Javascript的atob解码base64不能正确解码utf-8字符串