Jacob Phillips
Jacob Phillips

Reputation: 9274

Is it possible to manually add to a service worker cache?

I am trying to make an interface that works with service worker but it currently expects to be able to write to the cache itself.

If it is not possible, it would be helpful to know if an expired cache resource will be used when network is unavailable.

Edit specifically Response public constructors don't allow specifying the body data, and Cache.put() requires a Response.

Upvotes: 0

Views: 362

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56104

I am trying to make an interface that works with service worker but it currently expects to be able to write to the cache itself.

The Cache Storage API is useful inside of a service worker, but it isn't limited to just the ServiceWorkerGlobalScope. It's also exposed on normal web pages as window.caches. So you can read from and write to the same caches from either your web page or your service worker (or a web worker, for that matter).

If it is not possible, it would be helpful to know if an expired cache resource will be used when network is unavailable.

There's no concept of "expired cache resource" within the Cache Storage API. The Cache-Control headers in the cached Response are effectively ignored, if that's what you're asking about. So as long as a Response is stored in a cache, you can read it and make use of it. But nothing will be used automatically—you need to specifically set up a service worker's fetch event handler and add in logic that determines what happens in various scenarios. A good, generic overview of how to write that service worker code can be found in "The Offline Cookbook".

For instance, here's a fetch handler that will respond to all network requests by first going against the network (via fetch()) and if that rejects, tries to respond with a cached response for the same URL:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    fetch(event.request).catch(function() {
      return caches.match(event.request);
    })
  );
});

Upvotes: 1

Related Questions