我还没有找到明确的答案,但从我的实验来看,以下情况似乎是正确的:
服务工作人员无法访问或控制传统的浏览器缓存。这是故意的吗?有没有我还没有发现的方法可以做到这一点?
当我说“浏览器缓存”时,我并不是指的是 CacheStorage API 。我确实知道 Service Worker 具有对 CacheStorage API 的完全访问权限。我的意思是,当浏览器开发工具的网络选项卡中的请求说“来自内存缓存”而不是“来自服务 worker ”或直接来自实际网络请求时使用的缓存。
最佳答案
如果“浏览器缓存”指的是 http 缓存,那么服务工作线程可以使用 fetch() 函数访问它。要控制它与 http 缓存交互的方式,您可以在请求初始值设定项中指定 RequestCache
枚举值。所以类似:
// 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' });
这显示了创建 Request
对象的完整方法以及直接使用 fetch()
的简写。在任何一种情况下都可以传递缓存值。
获取规范包含 RequestCache
值的完整列表:
https://fetch.spec.whatwg.org/#requestcache
没有直接的编程 API 来检查或修改 http 缓存。
关于javascript - Service Worker 可以访问浏览器缓存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57205580/