在浏览器中检测离线模式的最佳方法是什么?

Vai*_*hav 4 javascript ajax offline-mode

我有一个Web应用程序,其中有许多Ajax组件在页面内经常刷新(它是各种各样的仪表板).

现在,我想为页面添加功能,以便在没有Internet连接时,页面的当前内容不会更改,并且页面上会显示一条消息,指出页面处于脱机状态(当前,这些不同的小工具都在页面尝试刷新自己,发现没有连接,他们的旧数据消失了).

那么,最好的方法是什么?

Dan*_*Dan 12

navigator.onLine
Run Code Online (Sandbox Code Playgroud)

那应该做你要问的.

您可能想要检查更新页面的任何代码.例如:

if (navigator.onLine) {
    updatePage();
} else {
    displayOfflineWarning();
}
Run Code Online (Sandbox Code Playgroud)


And*_*ges 3

处理此问题的一种方法可能是使用显式超时方法扩展 XmlHTTPRequest 对象,然后使用该方法确定您是否在脱机模式下工作(即,对于不支持 navigator.onLine 的浏览器)。以下是我在一个站点(使用Prototype库的站点)上实现 Ajax 超时的方法。10 秒(10,000 毫秒)后,它中止调用并调用 onFailure 方法。

/**
 * Monitor AJAX requests for timeouts
 * Based on the script here: http://codejanitor.com/wp/2006/03/23/ajax-timeouts-with-prototype/
 *
 * Usage: If an AJAX call takes more than the designated amount of time to return, we call the onFailure
 *        method (if it exists), passing an error code to the function.
 *
 */

var xhr = {
    errorCode: 'timeout',
    callInProgress: function (xmlhttp) {
        switch (xmlhttp.readyState) {
            case 1: case 2: case 3:
                return true;
            // Case 4 and 0
            default:
                return false;
        }
    }
};

// Register global responders that will occur on all AJAX requests
Ajax.Responders.register({
    onCreate: function (request) {
        request.timeoutId = window.setTimeout(function () {
            // If we have hit the timeout and the AJAX request is active, abort it and let the user know
            if (xhr.callInProgress(request.transport)) {
                var parameters = request.options.parameters;
                request.transport.abort();
                // Run the onFailure method if we set one up when creating the AJAX object
                if (request.options.onFailure) {
                    request.options.onFailure(request.transport, xhr.errorCode, parameters);
                }
            }
        },
        // 10 seconds
        10000);
    },
    onComplete: function (request) {
        // Clear the timeout, the request completed ok
        window.clearTimeout(request.timeoutId);
    }
});
Run Code Online (Sandbox Code Playgroud)

  • window.navigator.onLine 仅告知浏览器是否设置为离线模式(至少在 Firefox 中)。如果互联网连接丢失,它仍然会显示为 true,至少对我来说是这样。 (2认同)