我遇到了navigator.onLine属性的问题.
我正在运行WAMP的本地信息亭运行一个简单的网站.
在我测试它的笔记本电脑上它有效.我关闭WiFi并显示警告框.在运行WAMP软件的自助服务终端上断开互联网连接不会产生错误状态.有什么想法吗?
var online = navigator.onLine;
if (online == false) {
alert("Sorry, we currently do not have Internet access.");
location.reload();
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*nte 48
关于navigator.onLine的 MDN :
在Chrome和Safari中,如果浏览器无法连接到局域网(LAN)或路由器,则它处于脱机状态; 所有其他条件都返回true.因此,虽然您可以假设浏览器在返回false值时处于脱机状态,但您不能认为真值必然意味着浏览器可以访问Internet.
如上所述,此属性不可信,因此,在我看来,最好的解决方法是对服务器端页面的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!");
}
);
Run Code Online (Sandbox Code Playgroud)
如果您使用的是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
}
});
Run Code Online (Sandbox Code Playgroud)