ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-07-11 18:34:31  阅读:171  来源: 互联网

标签:javascript ajax offline-mode


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

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

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

解决方法:

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

标签:javascript,ajax,offline-mode
来源: https://codeday.me/bug/20190711/1434745.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有