navigator.onLine并不总是有效

Jak*_*ako 26 javascript

我遇到了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)

  • 我想补充一点,如果你想检查除你自己的网站之外的任何其他网站(在那里打电话),例如从www.YourSite.com`到`https //:google.com`,那么如果目标网站(`google.com`)不接受"跨站点呼叫",则会引发错误.如果我错了,请纠正我. (4认同)
  • 也可以调用jQuery.ajax,然后监听error: function(x, e)。如果 x.status ===0 表示网络有问题,可能离线 (2认同)

Ahm*_*aki 5

如果您使用的是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)