簡體   English   中英

JavaScript檢測用戶是否離線

[英]JavaScript detect if user is offline

我目前正在開發Web應用程序。 我正在使用Appcache。 因此,我要做的實際上是非常簡單的:如果用戶在沒有Internet連接的情況下加載頁面,他將看到帶有文本“ offline”的按鈕,否則將看到文本“ online”的按鈕。 我的第一種方法是使用offline.js,但無法正確檢測用戶何時上線/下線。

所以我嘗試了這段代碼:

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;
    }
}

但是看來,當通過AppCache加載頁面時,XHR-Requests將失敗。 不能選擇使用navigator.onLine ,因為我們大多數用戶都在使用Chrome。

有解決方案嗎? 謝謝

navigator.onLine 確實可以在Chrome中使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM