javascriptservice-workerbrowser-cachecachestorage

Can the service worker access browser cache?


I haven't found a clear answer to this but from my experiments the following appears true:

Service workers have no access to or control over the traditional browser cache. Is this intended? Are there ways to do this that I haven't discovered yet?

When I say "browser cache" I don't mean the CacheStorage API. I do know that the service worker has full access to the CacheStorage API. I mean the cache which is used when requests in the network tab of browser dev tools say "from memory cache" as opposed to "from service worker" or just straight up from an actual network request.


Solution

  • If by "browser cache" you mean the http cache, then yes the service worker can access it using the fetch() function. To control how it interacts with the http cache you can specify a RequestCache enumeration value in your request initializer. So something like:

    // completely bypass the http cache when loading url
    let r = new Request(url, { cache: 'no-store' });
    fetch(r);
    
    // revalidate any http cache entry for url
    fetch(url, { cache: 'no-cache' });
    
    // force use of the http cache entry even if its stale, otherwise load from network
    fetch(url, { cache: 'force-cache' });
    
    // Only return a response if the http cache entry is present.  Throws for cross-origin
    // URLs.
    fetch(url, { mode: 'same-origin', cache: 'only-if-cached' });
    

    This shows both the full method of creating a Request object and the shorthand of using fetch() directly. The cache values can be passed in either case.

    The fetch spec contains the full list of RequestCache values:

    https://fetch.spec.whatwg.org/#requestcache

    There is no direct programatic API to inspect or modify the http cache.