处理定制服务人员的响应

时间:2019-10-10 12:22:05

标签: javascript service-worker progressive-web-apps

我正在尝试从服务人员返回自定义响应。从网络中获取请求但不可用时,从缓存中检查是否还是失败,我想根据请求的URL类型返回自定义的html响应或image

我有下面的代码,但是它不起作用,请提供任何想法,让我知道如何为我的sw获得此工作或更好的解决方案。

Here is my full SW script

示例代码

self.addEventListener('fetch', function (event) {
    var cacheType = (function () {
        if (is('image', event.request.url)) {
            return cacheImage;
        } else if (is('html', event.request.url)) {
            return cacheHtml;
        } else if (event.request.headers.get('accept').includes('text/css') || event.request.headers.get('accept').includes('*/*')) {
            return cacheFiles;
        } else {
            return cacheFiles;
        }
    })();

    // Jump to offline page when there is no network
    if (!self.navigator.onLine) {
        //console.log('[ServiceWorker] No network, jump offline page');
        event.respondWith(
            caches.match(event.request).then(function (response) {
                return caches.match(offlineUrl);
            })
        );
    } else {
        event.respondWith(
            caches.open(cacheType).then(function (cache) {
                return cache.match(event.request).then(function (response) {
                    if (response) {
                        // console.log('[ServiceWorker]Take in the cache %s', event.request.url);
                        if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') return;

                        setTimeout(function(){
                            fetch(event.request).then(function(response) {
                                if(isValidResponse(response, event.request.url)) {
                                    caches .open(cacheType) .then(function (cache) {
                                        if(event.request.method == "GET" && (response.status === 200 || response.status === 0)){
                                            cache.put(event.request, response);
                                        }
                                    });
                                }
                            });
                        }, 2000);
                        return response || unableToResolve();
                    }

                    if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') return;

                    return fetch(event.request).then(function (response) {
                        if(event.request.method == "GET" && (response.status === 200 || response.status === 0)){
                            cache.put(event.request, response.clone());
                        }
                         return response ||  unableToResolve();
                    }).catch(function(err){
                         return unableToResolve();
                    });
                });

                function unableToResolve () {
                    console.log('[ServiceWorker] fetch request failed in both cache and network');
                    return new Response('<h1>Service Unavailable</h1>', {
                        status: 503,
                        statusText: 'Service Unavailable',
                        headers: new Headers({
                          'Content-Type': 'text/html'
                        })
                    });
                }

            })
        );
    }
});

我一直没有尝试过。

1 个答案:

答案 0 :(得分:0)

从您的评论中我可以理解。

  

我想要的是,当脱机并且请求url不在高速缓存中时,返回来自canableToResolve的自定义html

离线时!self.navigator.onLine为真。

在这种情况下,您当前的代码未使用unableToResolve

if (!self.navigator.onLine) {
    event.respondWith(async function() {
   const cachedResponse = await caches.match(event.request);
   if (cachedResponse) {
     return cachedResponse;
   }else{
     return unableToResolve();
     // Or you can return caches.match(offlineUrl); as your existing code does.
   }
  }());
}