navigator.onLine not always working

后端 未结 2 1301
情话喂你
情话喂你 2020-11-27 05:19

I\'m having an issue with the navigator.onLine property.

I\'m running a simple website from a local kiosk running on a WAMP.

On my laptop when I test this it

2条回答
  •  孤城傲影
    2020-11-27 05:49

    MDN about 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.

    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!");
        }
    );
    

提交回复
热议问题