【发布时间】:2017-10-06 13:35:24
【问题描述】:
我正在使用 Service Worker 进行离线工作。所以对于每个 Fetch 请求,我将它存储在缓存中。
现在,
我希望服务人员会提出请求,并将其存储起来以备下次使用。
问题是当我使用 fetch(myUrl).then... 时,服务工作者中的 Fetch Listener self.addEventListener('fetch', function(e)... 没有捕捉到它。
我不想重复代码.. 有什么想法吗?
获取监听器是:
self.addEventListener('fetch', function(e) {
// e.respondWidth Responds to the fetch event
e.respondWith(
// Check in cache for the request being made
caches.match(e.request)
.then(function(response) {
// If the request is in the cache
if ( response ) {
console.log("[ServiceWorker] Found in Cache", e.request.url, response);
// Return the cached version
return response;
}
// If the request is NOT in the cache, fetch and cache
var requestClone = e.request.clone();
return fetch(requestClone)
.then(function(response) {
if ( !response ) {
console.log("[ServiceWorker] No response from fetch ")
return response;
}
var responseClone = response.clone();
// Open the cache
caches.open(cacheName).then(function(cache) {
// Put the fetched response in the cache
cache.put(e.request, responseClone);
console.log('[ServiceWorker] New Data Cached', e.request.url);
// Return the response
return response;
}); // end caches.open
// returns the fresh response (not cached..)
return response;
})
.catch(function(err) {
console.log('[ServiceWorker] Error Fetching & Caching New Data', err);
});
}) // end caches.match(e.request)
.catch(function(e){
// this is - if we still dont have this in the cache !!!
console.log("[ServiceWorker] ERROR WITH THIS MATCH !!!",e, arguments)
})// enf of caches.match
); // end e.respondWith
});
【问题讨论】:
-
你确定你的 service worker 已经注册了吗?