Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceWorker - Cache all failed post requests when offline and resubmit when online

My service worker at the moment successfully achieves the following:

  • It caches all pages visited when online
  • It only returns cached pages when offline

My application has the ability for users to input signatures, which are submitted via ajax automatically. I am attempting to capture this post request in my service worker when they're offline, and resubmit the same request as soon as they're online.

Below is a sample of my serviceworker file.

self.addEventListener('fetch', function(event) {
    // Intercept all fetch requests from the parent page
    event.respondWith(
        caches.match(event.request)
        .then(function(response) {
            // Immediately respond if request exists in the cache and user is offline
            if (response && !navigator.onLine) {
                return response;
            }


            // IMPORTANT: Clone the request. A request is a stream and
            // can only be consumed once. Since we are consuming this
            // once by cache and once by the browser for fetch, we need
            // to clone the response
            var fetchRequest = event.request.clone();

            // Make the external resource request
            return fetch(fetchRequest).then(
                function(response) {
                // If we do not have a valid response, immediately return the error response
                // so that we do not put the bad response into cache
                if (!response || response.status !== 200 || response.type !== 'basic') {
                    return response;
                }

                // IMPORTANT: Clone the response. A response is a stream
                // and because we want the browser to consume the response
                // as well as the cache consuming the response, we need
                // to clone it so we have 2 stream.
                var responseToCache = response.clone();

                // Place the request response within the cache
                caches.open(CACHE_NAME)
                .then(function(cache) {
                    if(event.request.method !== "POST")
                    {
                        cache.put(event.request, responseToCache);
                    }
                });

                return response;
            }
            );
        })
    );
});

I am trying to figure out the best way to incorporate this? Is anyone able to shed some light?

like image 568
Matt Avatar asked Oct 18 '25 05:10

Matt


1 Answers

I have achieved my desired result with the following code underneath the following comments.

// Cache signature post request
    //This retrieves all the information about the POST request including the formdata body, where the URL contains updateSignature.
// Resubmit offline signature requests
    //This resubmits all cached POST results and then empties the array.

self.addEventListener('fetch', function(event) {
    // Intercept all fetch requests from the parent page
    event.respondWith(
        caches.match(event.request)
        .then(function(response) {
            // Cache signature post request
            if (event.request.url.includes('updateSignature') && !navigator.onLine) {
                var request = event.request;
                var headers = {};
                for (var entry of request.headers.entries()) {
                    headers[entry[0]] = entry[1];
                }
                var serialized = {
                    url: request.url,
                    headers: headers,
                    method: request.method,
                    mode: request.mode,
                    credentials: request.credentials,
                    cache: request.cache,
                    redirect: request.redirect,
                    referrer: request.referrer
                };
                request.clone().text().then(function(body) {
                    serialized.body = body;
                    callsToCache.push(serialized);
                    console.log(callsToCache);
                });     
            }
            // Immediately respond if request exists in the cache and user is offline
            if (response && !navigator.onLine) {
                return response;
            }
            // Resubmit offline signature requests
            if(navigator.onLine && callsToCache.length > 0) {
                callsToCache.forEach(function(signatureRequest) {
                    fetch(signatureRequest.url, {
                        method: signatureRequest.method,
                        body: signatureRequest.body
                    })
                });
                callsToCache = [];
            }


            // IMPORTANT: Clone the request. A request is a stream and
            // can only be consumed once. Since we are consuming this
            // once by cache and once by the browser for fetch, we need
            // to clone the response
            var fetchRequest = event.request.clone();

            // Make the external resource request
            return fetch(fetchRequest).then(
                function(response) {
                // If we do not have a valid response, immediately return the error response
                // so that we do not put the bad response into cache
                if (!response || response.status !== 200 || response.type !== 'basic') {
                    return response;
                }

                // IMPORTANT: Clone the response. A response is a stream
                // and because we want the browser to consume the response
                // as well as the cache consuming the response, we need
                // to clone it so we have 2 stream.
                var responseToCache = response.clone();

                // Place the request response within the cache
                caches.open(CACHE_NAME)
                .then(function(cache) {
                    if(event.request.method !== "POST")
                    {
                        cache.put(event.request, responseToCache);
                    }
                });

                return response;
            }
            );
        })
    );
});
like image 94
Matt Avatar answered Oct 19 '25 20:10

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!