如何在JavaScript中检测Internet连接是否离线?
当前回答
下面是我拥有的一个辅助实用程序片段。这是带名称空间的javascript:
network: function() {
var state = navigator.onLine ? "online" : "offline";
return state;
}
你应该使用这个方法检测,否则发射一个'替代'的方式来做这件事。这将是我们所需要的全部。其他的方法是hack。
其他回答
您可以使用$.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!');
}
}
});
如何发送一个不透明的http请求到google.com与无cors?
fetch('https://google.com', {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'no-cors',
}).then((result) => {
console.log(result)
}).catch(e => {
console.error(e)
})
设置no-cors的原因是,即使在我的pc上取消网络连接时,我也收到了cors错误。所以不管有没有网络连接,我都被封锁了。添加no-cors使请求不透明,这显然似乎绕过cors,并允许我只是简单地检查我是否可以连接到谷歌。
供参考:我在这里使用fetch进行http请求。 https://www.npmjs.com/package/fetch
下面是我拥有的一个辅助实用程序片段。这是带名称空间的javascript:
network: function() {
var state = navigator.onLine ? "online" : "offline";
return state;
}
你应该使用这个方法检测,否则发射一个'替代'的方式来做这件事。这将是我们所需要的全部。其他的方法是hack。
我不得不为一个与学校有很多合作的客户制作一个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();
}
});
}
几乎所有主流浏览器现在都支持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年的更新已经不是他的了。
推荐文章
- 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字符串