我正在使用服务人员来缓存和获取文件。
这些文件在在线模式下被缓存,但是当我切换到离线模式时,chrome 开发者工具中的缓存存储是空的。我无法弄清楚问题所在。
任何帮助表示赞赏。
const cacheName = 'myCacheVersion1';
var filesToCache = [
'/',
'/service-worker/offline-page.html',
'/service-worker/sw.js'
]
const offlineUrl = 'https://gmc-test.mytrah.com/service-worker/offline-page.html';
this.addEventListener('install', event => {
event.waitUntil(
caches.open(cacheName).then(function(cache){
console.log(offlineUrl);
return cache.addAll(filesToCache);
})
.then(() => self.skipWaiting())
);
})
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (key !== cacheName) {
console.log('[ServiceWorker] Removing old cache', key);
return caches.delete(key);
}
}));
})
);
return self.clients.claim();
});
this.addEventListener('fetch', event => {
console.log(event.request);
event.respondWith(
fetch(event.request).catch(() => caches.match(event.request))
)
});`
上面显示的是服务 worker 代码。
提前致谢
最佳答案
问题
我在为服务人员工作时遇到了类似的问题。当我将网络标记为离线时,缓存曾经从缓存存储中消失。发生这种情况的问题是因为我将 service worker 文件保存在 javascripts
中。文件夹。就像 OP 放置在 service-worker
中一样文件夹。现在上述导致范围问题。
使固定
因此,为了让您的服务人员工作(没有双关语),你需要将你的 service worker 文件移动到根目录 (在您这样做时强调安全性)。
文档
如MDN引号:
The service worker will only catch requests from clients under the service worker's scope.
The max scope for a service worker is the location of the worker.
您还可以通过传递
scope
来设置范围注册 Service Worker 时的路径,例如navigator.serviceWorker
.register('/cache-worker.js', {
scope: '/some-folder'
/* but again, you can never put your service worker inside a dir and
try to set a scope which is outside of the service worker dir.
It can always be at a lower level than where your service worker file resides..
})
...
关于javascript - 为什么chrome开发者工具中的缓存存储在离线模式下会变空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52109971/