2

I have a progressive web-app, which speaks to an API. The calls to this api get cached by a service worker, which works great.

But now, I want to add a reload-button, which ideally forces the service worker to try to bypass the cache and update it if successful, also it should not return the cached result if a connection could not be made.

I am a bit unsure how to solve this. I am using the sw-toolbox.

Leander
  • 1,322
  • 4
  • 16
  • 31

2 Answers2

1

Based on your description, you are using the application cache. It can be accessed from the app fronted independent of the sw-tool box.

  function onReloadButtonClicked(event) {
      //Check for browser cache support
      if ('caches' in window) {
        //Update cache if network query is successful
        caches.open('your_cache_name')
          .then(function(cache) {
            cache.add('your_url');
          }).catch(function(err) {
            // Do something with the error
          });
      }
    }
Jose Cherian
  • 7,207
  • 3
  • 36
  • 39
1

All requests go through the fetch callback which receives a request object. Thus, before returning a cached response you can look for an additional header parameter (you need to include it into your request to API) to skip the logic returning cached response.

Dmytro Nesteriuk
  • 8,315
  • 1
  • 18
  • 14