Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the right way to implement offline fallback with workbox

I am implementing PWA into my project, I have setted up the serviceworker.js, and I am using workbox.js for cache routing and strategies.

1- I add the offline page to cache on install event, when a user first visit the site:

/**
 * Add on install
 */
self.addEventListener('install', (event) => {
  const urls = ['/offline/'];
  const cacheName = workbox.core.cacheNames.runtime;
  event.waitUntil(caches.open(cacheName).then((cache) => cache.addAll(urls)))
});

2- Catch & cache pages with a specific regex, like these:

https://website.com/posts/the-first-post

https://website.com/posts/

https://website.com/articles/

workbox.routing.registerRoute(
  new RegExp('/posts|/articles'),
  workbox.strategies.staleWhileRevalidate({
     cacheName: 'pages-cache' 
  })
);

3- Catch errors and display the offline page, when there's no internet connection.

/**
 * Handling Offline Page fallback
 */
this.addEventListener('fetch', event => {
  if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
        event.respondWith(
          fetch(event.request.url).catch(error => {
              // Return the offline page
              return caches.match('/offline/');
          })
    );
  }
  else{
        // Respond with everything else if we can
        event.respondWith(caches.match(event.request)
                        .then(function (response) {
                        return response || fetch(event.request);
                    })
            );
      }
});

Now this is working for me so far if I visit for example: https://website.com/contact-us/ but if I visit any url within the scope I defined earlier for "pages-cache" like https://website.com/articles/231/ this would not return the /offline page since it's not in the user cache, and I would get a regular browser error.

There's an issue in how errors are handled, when there's a specific caching route by workbox.

Is this the best method to apply for offline fallback? how can I catch errors from these paths: '/articles' & '/posts' and display an offline page?

Please refer as well to this answer where there's a different approach to applying the fallack with workbox, I tried it as well same results. Not sure which is the accurate approach for this.

like image 558
Kash Avatar asked Nov 27 '18 16:11

Kash


People also ask

What is fallback response?

The fallback interaction is triggered when your chatbot doesn't recognize the user's message. You can use it to ask the user to reword their question, show answers they can choose from, or transfer them to a human agent when integrated with LiveChat.

What is the use of fallback HTML page?

A fallback is a generic, one-size-fits-all response that's a better placeholder than what the browser would provide by default when a request fails. Some examples are: An alternative to the "missing image" placeholder. An HTML alternative to the standard "no network connection available" page.

What is fallback page?

Fallback pages are the last line of defense if your landing page is offline or not found.


1 Answers

I found a way to do it right with workbox. For each route I would add a fallback method like this:

const offlinePage = '/offline/';
/**
 * Pages to cache
 */
workbox.routing.registerRoute(/\/posts.|\/articles/,
  async ({event}) => {
    try {
      return await workbox.strategies.staleWhileRevalidate({
          cacheName: 'cache-pages'
      }).handle({event});
    } catch (error) {
      return caches.match(offlinePage);
    }
  }
);

In case of using network first strategy this is the method:

/**
 * Pages to cache (networkFirst)
 */
var networkFirst = workbox.strategies.networkFirst({
  cacheName: 'cache-pages' 
});

const customHandler = async (args) => {
  try {
    const response = await networkFirst.handle(args);
    return response || await caches.match(offlinePage);
  } catch (error) {
    return await caches.match(offlinePage);
  }
};

workbox.routing.registerRoute(
  /\/posts.|\/articles/, 
  customHandler
);

More details at workbox documentation here: Provide a fallback response to a route

like image 86
Kash Avatar answered Oct 25 '22 05:10

Kash