navigator.onLine并不总是有效 [英] navigator.onLine not always working
问题描述
我遇到了navigator.onLine属性的问题。
I'm having an issue with the navigator.onLine property.
我正在运行WAMP的本地信息亭运行一个简单的网站。
I'm running a simple website from a local kiosk running on a WAMP.
在我的笔记本电脑上进行测试时,它可以正常工作。我关闭WiFi并显示警告框。在运行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?
var online = navigator.onLine;
if (online == false) {
alert("Sorry, we currently do not have Internet access.");
location.reload();
}
推荐答案
MDN关于 navigator.onLine :
在Chrome和Safari中,如果浏览器无法连接到局域网(LAN)或路由器,则它处于脱机状态;所有其他条件都返回true。因此,虽然您可以假设浏览器在返回false值时处于脱机状态,但您不能认为真值必然意味着浏览器可以访问互联网。
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.
如上所述,此属性不可信,因此,在我看来,最佳解决方法是对服务器端页面的ajax调用。如果浏览器处于脱机状态,则连接将失败,因此将调用 onerror
事件。否则,将调用 onload
事件:
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 onerror
event will be called. Otherwise, the onload
event is called:
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!");
}
);
这篇关于navigator.onLine并不总是有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!