【问题标题】:Service worker not returning custom offline page it is instead returning the default "offline" page服务工作者不返回自定义离线页面,而是返回默认的“离线”页面
【发布时间】:2021-02-05 13:06:20
【问题描述】:

我有一个服务人员,如果您处于离线状态,我想返回一个离线页面。我意识到你必须先缓存离线页面,所以我这样做了。当我将其缓存并使用 chrome 开发工具将网络限制为脱机时,它显示了默认的脱机页面!我不知道如何在离线时调出页面。如果这会改变任何事情,我正在使用 chromebook。这是我的代码(顺便说一下,我对服务人员完全陌生):

this.addEventListener('install', function(event) {
 event.waitUntil(
 caches.open('v1').then(function(cache) {
   return cache.addAll(['../offline.html','../images/ico/ico.jpg']); 
 })
 );
});
this.addEventListener('fetch', function(event) {
    event.respondWith(
       caches.match(event.request)
           .then(function(response) {
               // If fetch fails, we return offline.html from cache.
               return fetch(event.request)
                   .catch(err => {
                       return caches.match('../offline.html');
                   });
           }
       )
   );
});

【问题讨论】:

标签: javascript caching service-worker


【解决方案1】:

用这个替换您的 fetch 事件代码。对于每个请求,都会调用您的 fetch 事件,它会检查您的请求是否在缓存文件列表中找到,然后它将从那里提供文件,否则它将进行 fetch 调用以从服务器获取文件。

self.addEventListener('fetch', (event) => {
  // We only want to call event.respondWith() if this is a navigation request
  // for an HTML page.
  if (event.request.mode === 'navigate') {
    event.respondWith((async () => {
      try {
        // First, try to use the navigation preload response if it's supported.
        const preloadResponse = await event.preloadResponse;
        if (preloadResponse) {
          return preloadResponse;
        }

        const networkResponse = await fetch(event.request);
        return networkResponse;
      } catch (error) {
        // catch is only triggered if an exception is thrown, which is likely
        // due to a network error.
        // If fetch() returns a valid HTTP response with a response code in
        // the 4xx or 5xx range, the catch() will NOT be called.
        console.log('Fetch failed; returning offline page instead.', error);

        const cache = await caches.open(CACHE_NAME);
        const cachedResponse = await cache.match(OFFLINE_URL);
        return cachedResponse;
      }
    })());
  }

  // If our if() condition is false, then this fetch handler won't intercept the
  // request. If there are any other fetch handlers registered, they will get a
  // chance to call event.respondWith(). If no fetch handlers call
  // event.respondWith(), the request will be handled by the browser as if there
  // were no service worker involvement.
});

【讨论】:

  • 但是我想获取一个离线页面,这将显示用户离线而不是添加缓存版本。那可能吗?我不能把底部的return fetch(event.request);改成return fetch('page-to-offline-html-page.html');吗?
  • 是的,这是可能的。将您的 offline.html 页面添加到您的缓存列表中。
  • (抱歉这么久才回复,正忙于其他事情)仍然无法正常工作。仍然给出默认的离线页面(chrome离线页面)。另外,我猜 await 不适用于服务人员。
  • 它现在可以工作了(我只是在根目录中没有它)。谢谢,我会将您的问题标记为答案。
猜你喜欢
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-31
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 2020-05-05
相关资源
最近更新 更多