[英]Using service worker to catch network error
I have a service worker for my site, but I'm not sure how to get it to handle when there is a network error, I've looked through Mozilla's guides but when I run the worker offline it says that a network error was passed to the respondWith
function, and the catch promise seems to not respond with the cached data. 我有一个服务工作者为我的网站,但我不知道如何在出现网络错误时处理它,我查看了Mozilla的指南,但是当我离线运行工作程序时,它说网络错误已通过对于
respondWith
函数,catch承诺似乎没有响应缓存数据。
this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
return cache.addAll([
'/',
'/favicon.ico',
'/f3be2e30f119a1a9b0fdee9fc1f477a9',
'/index.html',
'/sw.js'
]);
})
);
});
this.addEventListener('fetch', function(event) {
var response;
event.respondWith(caches.match(event.request).catch(function() {
return fetch(event.request);
})).then(function(r) {
response = r;
caches.open('v1').then(function(cache) {
cache.put(event.request, response);
});
return response.clone();
}).catch(function(event) {
console.log(event, 'borken');
return caches.match(event.request);
});
});
You're calling then
on the result of the call to event.respondWith
, which is undefined. 你打电话
then
在调用的结果event.respondWith
,这是不确定的。
You should chain your then
call after the call to catch
: 你应该链中的
then
调用后调用catch
:
var response;
event.respondWith(
caches.match(event.request)
.catch(function() {
return fetch(event.request);
})
.then(function(r) {
response = r;
Not: 不:
var response;
event.respondWith(
caches.match(event.request)
.catch(function() {
return fetch(event.request);
})
)
.then(function(r) {
response = r;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.