Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

javascript - navigator.onLine not always working

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 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();

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...