Javascript navigator.onLine 并不总是有效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14283124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
navigator.onLine not always working
提问by Jako
I'm having an issue with the navigator.onLine property.
我遇到了 navigator.onLine 属性的问题。
I'm running a simple website from a local kiosk running on a WAMP.
我正在从在 WAMP 上运行的本地信息亭运行一个简单的网站。
On my laptop when I test this it works. I turn off WiFi and the alert box shows up. Disconnecting the internet on the kiosk running the WAMP software does not produce the false status. Any ideas why?
在我的笔记本电脑上,当我测试它时,它可以工作。我关闭了 WiFi 并且出现了警告框。在运行 WAMP 软件的信息亭上断开互联网连接不会产生错误状态。任何想法为什么?
var online = navigator.onLine;
if (online == false) {
alert("Sorry, we currently do not have Internet access.");
location.reload();
}
回答by Danilo Valente
MDN about navigator.onLine:
MDN 关于navigator.onLine:
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.
在 Chrome 和 Safari 中,如果浏览器无法连接到局域网(LAN)或路由器,则为离线;所有其他条件返回真。因此,虽然您可以假设浏览器在返回假值时处于离线状态,但您不能假设真值必然意味着浏览器可以访问互联网。
As described above, this property is not trustable, so, in my opinion, the best workaround is an ajax call to a server-side page. If the browser is offline, then the connection will fail and, thus, the onerrorevent will be called. Otherwise, the onloadevent is called:
如上所述,此属性不可信,因此,在我看来,最好的解决方法是对服务器端页面进行 ajax 调用。如果浏览器离线,则连接将失败,因此onerror将调用该事件。否则,onload事件被调用:
function isOnline(no,yes){
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
if(yes instanceof Function){
yes();
}
}
xhr.onerror = function(){
if(no instanceof Function){
no();
}
}
xhr.open("GET","anypage.php",true);
xhr.send();
}
isOnline(
function(){
alert("Sorry, we currently do not have Internet access.");
},
function(){
alert("Succesfully connected!");
}
);
回答by Ahmad Mobaraki
As Danilo Valentepointed: navigator.onLineproperty is not trustable,
正如所Danilo Valente指出的:navigator.onLine财产是不可信的,
But NOT every error in ajax response means you are disconnected from the internet! It may be an API error (403,500,404 ....)
但并非 ajax 响应中的每个错误都意味着您与互联网断开连接!可能是 API 错误 (403,500,404 ....)
If you are using axios, you can distinguish these errors like this:
如果您正在使用axios,您可以像这样区分这些错误:
axios.request(options).catch(function(error) {
if (!error.response) {
// network error (server is down or no internet)
} else {
// http status code
const code = error.response.status
// data from server while error
const response = error.response.data
}
});

