简体   繁体   中英

JavaScript detect if user is offline

I'm currently working on a web application. I'm using Appcache. So what I want to do is actually dead simple: If the user loads the page without an internet connection, he'll see a button with the text "offline", otherwise with the text "online". My first approach was to use offline.js, but it wasn't correctly detecting when the user was on/offline.

So I've tried this code:

function serverReachable() {
    // IE vs. standard XHR creation
    var x = new (window.ActiveXObject || XMLHttpRequest)("Microsoft.XMLHTTP"),
        s;
    x.open(
        // requesting the headers is faster, and just enough
        "HEAD",
        // append a random string to the current hostname,
        // to make sure we're not hitting the cache
        "//" + window.location.hostname + "/?rand=" + Math.random(),
        // make a synchronous request
        false
    );
    try {
        x.send();
        s = x.status;
        // Make sure the server is reachable
        return (s >= 200 && s < 300 || s === 304);
        // catch network & other problems
    } catch (e) {
        return false;
    }
}

But it seems, that XHR-Requests will fail when the page is loaded via AppCache. Using navigator.onLine is no option, because most of our users are using Chrome.

Is there a solution? Thank you

navigator.onLine 确实可以在Chrome中使用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM