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

时间:2020-03-06 14:22:30  来源:igfitidea点击:

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

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

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

解决方案

navigator.onLine

那应该可以满足要求。

我们可能想要检查是否有更新页面的任何代码。例如:

if (navigator.onLine) {
    updatePage();
} else {
    displayOfflineWarning();
}

看来我们已经回答了自己的问题。如果小工具发送了请求并且超时,则不要更新它们。如果足够,请显示"页面已脱机"消息。

请参阅HTML 5规范草案。我们需要navigator.onLine。并非所有浏览器都支持它。 Firefox 3和Opera 9.5都可以。

听起来好像我们是在试图掩盖问题而不是解决问题。如果失败的请求导致小部件清除其数据,那么我们应该修复代码,以便除非收到响应,否则它不会尝试更新小部件,而不是尝试提前确定请求是否成功。

嗯,实际上,现在我对此进行了研究,它要复杂得多。在John Resig的博客和Mozilla网站上阅读这些链接。无论如何,上面的海报也可能很好地说明了要求,因此,当它们失败时,我们应该能够解决问题。

解决此问题的一种方法可能是使用显式超时方法扩展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);
    }
});

我认为Google Gears具有这种功能,也许我们可​​以检查一下它们是如何做到的。

拨打一个可靠的目的地的电话,或者说一系列电话,如果用户有活动的网络连接,即使是像对google,yahoo和msn的令牌ping之类的简单操作,也应该经过并返回。如果至少有一个恢复为绿色,则表明已连接。

感谢所有回复。我将尝试用我最终所做的事情来更新问题。

使用相关的HTML5 API:在线/离线状态/事件。