Gari BN
Gari BN

Reputation: 1685

How can I access the resources saved in the cache by a ServiceWorker?

I'm trying to build a webpage that uses ServiceWorker. I followed this example (for Chrome 45+), which seems to cache some data. I tried to access the cached data but without success.

Is it possible to find the cached data via the Chrome console (similarly to Local Storage)? Is there any simple JS code I can run from the console to get it?

Upvotes: 5

Views: 2089

Answers (2)

StormyKnight
StormyKnight

Reputation: 607

Elevating this out of a comment:

The Cache Storage API is also exposed as window.caches in recent versions of Chrome, so you can execute that code from the DevTools in a controlled page, without going to the service worker DevTools. It's also exposed visually in the DevTools' Resources tab: twitter.com/jeffposnick/status/546494702842028032 – Jeff Posnick Sep 2 '15 at 17:51

With thanks to Jeff P.

Upvotes: 0

Brendan Ritchie
Brendan Ritchie

Reputation: 2345

Yes, you can see what's in the cache. Looking at the source code from the sample repository you're using, I see that it is storing the cached urls in a cache called CURRENT_CACHES['post-message']. If you're in the service worker (go to chrome://serviceworker-internals/, find the relevant service worker, and inspect it), this snippet of code will log the urls currently stored in that cache:

caches.open(CURRENT_CACHES['post-message']).then(function(cache) {
  cache.keys().then(function(requests) {
    var urls = requests.map(function(request) {
      return request.url;
    });
    console.log(urls.sort());
  });
});

Basically you're just opening the cache, calling keys() on it, and logging the url for each key (or cache record) that is returned.

Upvotes: 4

Related Questions