当使用服务工作者时,脱机页面不显示在提取功能中

Offline page is not showing in fetch function when using service worker?

本文关键字:显示 提取 功能 脱机 服务 服务工作 工作者      更新时间:2023-09-26

就在一天前,我刚开始学习有关Service Workers的知识。根据我的学习,我想创建一个离线应用程序。我已经创建了两个页面,即demo.htmloffline.html

我已经在测试服务器中发布了我的文件。它有SSL连接。当我通过键入https://example.com/sampleapp/其中demo.html页面是默认页面。我已经安装了服务工作者,缓存文件已下载到我的机器上。这是问题发生的地方,在禁用我的网络后,我正在刷新页面,这里它不会转到脱机页面,而是显示演示页。当我调试service worker.js并刷新页面时,在js文件中,它将转到fetch函数并将response.status返回为"OK",而不是转到我写的应该转到脱机页面的catch块。

现在,我没有刷新,而是在URL中提到演示页面https://example.com/sampleapp/demo.html,然后转到脱机页面。当我连接到网络后,如果我用上面相同的URL刷新页面,它会显示离线页面,而不是去演示页面。我不知道为什么会发生这种事。你能告诉我我写的代码是否正确吗?

请找到我的服务人员.js代码


    // [Working example](/serviceworker-cookbook/offline-fallback/).
    var CACHE_NAME = 'dependencies-cache';
    var REQUIRED_FILES = [
      'offline.html',
      'todo.js',
      'index.js',
      'app1.js'
    ];
    self.addEventListener('install', function(event) {
      // Put `offline.html` page into cache
        event.waitUntil(
        caches.open(CACHE_NAME)
          .then(function (cache) {
              // Add all offline dependencies to the cache
              console.log('[install] Caches opened, adding all core components' +
                'to cache');
              return cache.addAll(REQUIRED_FILES);
          })
          .then(function () {
              console.log('[install] All required resources have been cached, ' +
                'we''re good!');
              return self.skipWaiting();
          })
      );

      //  var offlineRequest = new Request('offline.html');
      //event.waitUntil(
      //  fetch(offlineRequest).then(function(response) {
      //    return caches.open('offline').then(function(cache) {
      //      console.log('[oninstall] Cached offline page', response.url);
      //      return cache.put(offlineRequest, response);
      //    });
      //  })
      //);
    });
    self.addEventListener('activate', function (event) {
        console.log("Ready for the demo");
    });
    self.addEventListener('fetch', function(event) {
      // Only fall back for HTML documents.
      var request = event.request;
      // && request.headers.get('accept').includes('text/html')
      if (request.method === 'GET') {
        // `fetch()` will use the cache when possible, to this examples
        // depends on cache-busting URL parameter to avoid the cache.
        event.respondWith(
          fetch(request).then(function(response){
              if (!response.ok) {
                  // An HTTP error response code (40x, 50x) won't cause the fetch() promise to reject.
                  // We need to explicitly throw an exception to trigger the catch() clause.
                  throw Error('response status ' + response.status);
              }
              return response;
          }).catch(function (error) {
            // `fetch()` throws an exception when the server is unreachable but not
            // for valid HTTP responses, even `4xx` or `5xx` range.
            //console.error(
            //  '[onfetch] Failed. Serving cached offline fallback ' +
            //  error
              //);
              return caches.open(CACHE_NAME).then(function (cache) {
                  return cache.match('offline.html');
              });
            //return caches.match('offline.html');
            //return caches.open('offline').then(function(cache) {
            //  return cache.match('offline.html');
            //});
          })
        );
      }
      // Any other handlers come here. Without calls to `event.respondWith()` the
      // request will be handled without the ServiceWorker.
    });

还可以找到我的index.js代码

if (navigator.serviceWorker.controller) {
  // A ServiceWorker controls the site on load and therefor can handle offline
  // fallbacks.
  debug(
    navigator.serviceWorker.controller.scriptURL +
    ' (onload)', 'controller'
  );
  debug(
    'An active service worker controller was found, ' +
    'no need to register'
  );
} else {
  // Register the ServiceWorker
  navigator.serviceWorker.register('service-worker.js', {
    scope: './'
  }).then(function(reg) {
    //debug(reg.scope, 'register');
    //debug('Service worker change, registered the service worker');
  });
}

// Debug helper
function debug(message, element, append) {
}

根据我对服务工作者的了解,在获取功能中,如果没有互联网连接,我可以显示离线页面。这是显示脱机页面的正确方式吗?还是我应该显示演示页面,然后在该页面中(如果没有互联网连接),然后将数据保存到Index DB?我还有一个问题,当有互联网连接时,我想检查IndexDB中是否有任何数据,如果有,然后将数据上传到服务器。在哪种情况下,我应该处理Activate或Fetch?

谢谢,
Jollyguy

我遇到了类似的问题,这是因为在我的服务工作者的早期版本中,我缓存了index.html。从服务工作者中删除后,它仍保持缓存状态,即使在脱机时也会继续加载。在您的情况下,我怀疑"/"是缓存的,但"/demo.html"不是,这可以解释您所看到的行为。

chrome开发工具中的分辨率是:

  1. 应用程序>服务人员>检查"重新加载时更新",然后刷新页面或
  2. 应用程序>清除存储>保留所有选定内容,然后单击"清除选定内容"