How can I get the size and / or number of items in the ServiceWorker cache?

ServiceWorker is the new api available in Chrome. One of the many things that it allows you to do is to intercept network requests and respond with a cached version. I implement the button "Accept this offline", which dynamically adds things to the cache. I would like to tell the user how much space I use and how many entries I put into the cache.

Is it possible to request a cache to get the number of elements in it? Can I tell you about the total size of the items cached in it?

+5
source share
2 answers

Apparently, you can use cacheName.keys().length , as shown in trained awe , you can also cycle through individual entries and calculate the total weight.

+2
source

To find the approximate size of the cache, you can do something like this:

 // returns approximate size of a single cache (in bytes) function cacheSize(c) { return c.keys().then(a => { return Promise.all( a.map(req => c.match(req).then(res => res.clone().blob().then(b => b.size))) ).then(a => a.reduce((acc, n) => acc + n, 0)); }); } // returns approximate size of all caches (in bytes) function cachesSize() { return caches.keys().then(a => { return Promise.all( a.map(n => caches.open(n).then(c => cacheSize(c))) ).then(a => a.reduce((acc, n) => acc + n, 0)); }); } 

There are a few caveats:

  • Counts only the response body size. (This may be partially corrected.)
  • Counts opaque responses. (This cannot be fixed.)
+1
source

Source: https://habr.com/ru/post/1212681/


All Articles