Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling fetch requests in Progressive Web App when offline

I have been following this tutorial on Progressive Web Apps and I am trying to find a way to present the user with some sort of message when the app is offline. My code so far is pretty much the same as the tutorial:

var cacheName = 'demoPWA-v1';
var filesToCache = [
    '/',
    '/index.html',
    '/js/app.js',
    '/icons/pwa-256x256.png'
];

self.addEventListener('install', function(e) {
    console.log('[demoPWA - ServiceWorker] Install event fired.');
    e.waitUntil(
        caches.open(cacheName).then(function(cache) {
            console.log('[demoPWA - ServiceWorker] Caching app shell...');
            return cache.addAll(filesToCache);
        })
    );
});

self.addEventListener('activate', function(e) {
    console.log('[demoPWA - ServiceWorker] Activate event fired.');
    e.waitUntil(
        caches.keys().then(function(keyList) {
            return Promise.all(keyList.map(function(key) {
                if (key !== cacheName) {
                    console.log('[demoPWA - ServiceWorker] Removing old cache...', key);
                    return caches.delete(key);
                }
            }));
        })
    );
    return self.clients.claim();
});

self.addEventListener('fetch', function(e) {
    console.log('[demoPWA - ServiceWorker] Fetch event fired.', e.request.url);
    e.respondWith(
        caches.match(e.request).then(function(response) {
            if (response) {
                console.log('[demoPWA - ServiceWorker] Retrieving from cache...');
                return response;
            }
            console.log('[demoPWA - ServiceWorker] Retrieving from URL...');
            return fetch(e.request);
        })
    );
});

When I check the Offline checkbox in Chrome under Application > Service Workers, I get a couple of errors, like you can see below:

enter image description here

I wonder if there is some way to deal with this errors and, while doing so, show a message of some sort to the user, informing them of the fact that they are offline.

like image 811
Angelos Chalaris Avatar asked Oct 18 '25 13:10

Angelos Chalaris


2 Answers

Below is the mods just to do an alert, you can then change the alert to say using Jquery or direct DOM to update your HTML page..

self.addEventListener('fetch', function(e) {
    console.log('[demoPWA - ServiceWorker] Fetch event fired.', e.request.url);
    e.respondWith(
        caches.match(e.request).then(function(response) {
            if (response) {
                console.log('[demoPWA - ServiceWorker] Retrieving from cache...');
                return response;
            }
            console.log('[demoPWA - ServiceWorker] Retrieving from URL...');
            return fetch(e.request).catch(function (e) {
               //you might want to do more error checking here too,
               //eg, check what e is returning..
               alert('You appear to be offline, please try again when back online');
            });
        })
    );
});
like image 179
Keith Avatar answered Oct 20 '25 03:10

Keith


Yes, what you are doing, it makes perfect sense, as long as you are sure that the cache is not empty, since you only intend to use it to display an offline warning.

The MDN code is really problematic and catch() is not working, I made some modifications and it worked, as for catch(), I haven't had time to solve the problem yet, if you find the solution first, let me know! Here's the code:

var CACHE_VERSION = 1;

// Smallest identifier for a specific version of the cache
var CURRENT_CACHES = {
  font: 'OFFLINE_CACHE' + CACHE_VERSION
};

self.addEventListener('fetch', function(event) {
 // console.log(event);
// We only want to call event.respondWith() if this is a GET request for an HTML document.
  if (event.request.method === 'GET') {
    console.log('Handling fetch event for', event.request.url);

  event.respondWith(

    // Opens the cache object that starts with 'font'
    caches.open(CURRENT_CACHES['font']).then(function(cache) {
      return cache.match(event.request).then(function(response) {
        if (response) {
          console.log('Found cached answer:', response);
          return response;
        } else {
        //Did not find answer in cache
        return fetch(event.request).then(function(fetchresponse) {
        console.log("Request Result - redirected:" + fetchresponse.redirected + ", status:" + fetchresponse.status + ", statusText:" + fetchresponse.statusText + ", type:" + fetchresponse.type + ", url:" + fetchresponse.url);
        if(fetchresponse.status == '200' || fetchresponse.status == '201' || fetchresponse.status == '202' || fetchresponse.status == '203' || fetchresponse.status == '204' || fetchresponse.status == '206'){
               return fetchresponse;    
         } else {
         console.log('The request returned http code 30*, 40* or 50*.');
         return false;
         }    
        }).catch(function(e) {
         //Offline version
        return new Response('<html><title></title><strong>Sorry, You are offline!</strong></html>', {"status" : 202, "headers" : {"Content-Type" : "text/html; charset=utf-8"}});
        });
        }
      }).catch(function(error) {
        //This .catch () doesn't seem to work, as I said, but it won't give you any problems, it just takes up space.

        // Handles exceptions that come from match () or fetch ().

        console.error('  Error:', error);

        throw error;
      });
    })
  );
  };
});
like image 35
Macedo_Montalvão Avatar answered Oct 20 '25 04:10

Macedo_Montalvão



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!