What is the best method for detecting offline mode in a browser?

I have a web application that has a number of Ajax components that update so often inside the page (this is a pivot table).

Now I want to add functionality to the page so that in the absence of an Internet connection the current content of the page does not change and a message appears on the page stating that the page is offline (currently, because these various gadgets on the page are trying to refresh themselves and find that there is no connection, their old data disappears).

So what is the best way to do this?

+3
source share
10 answers

, XmlHTTPRequest -, , , ( , navigator.onLine). , - Ajax (, Prototype). 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);
    }
});
+3
navigator.onLine

, .

, , , . :

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

, . , . , " ".

+4

. HTML 5. navigator.onLine. . Firefox 3 Opera 9.5 .

, , . , , , , , , .

+4

, , , . Mozilla. - , , . .

+2

, , , , - - , ping google, yahoo msn, - . , , .

+2

, google gears , , , .

+1

API HTML5: / /.

+1

. , .

0

, URL-, , URL- . , . , navigator.online

0

Source: https://habr.com/ru/post/1697144/


All Articles