首页 文章

使用服务工作者时,脱机页面未显示在获取功能中?

提问于
浏览
1

我刚刚开始学习服务工作者一天前 . 根据我的学习,我想创建一个离线应用程序 . 我创建了2页,即 demo.htmloffline.html . 我的目标是,当没有互联网连接时,我必须显示offline.html .

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

现在我没有刷新,而是将URL中的演示页面提到https://example.com/sampleapp/demo.html,然后进入离线页面 . 连接到网络后,如果我使用相同的上述URL刷新页面,它将显示离线页面而不是转到演示页面 . 我无法分辨为什么会发生这种情况 . 你能告诉我我写的代码是否正确吗?

请找我的 service-worker.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) {
}

根据我对服务工作者的理解,如果没有互联网连接,在获取功能中,我可以显示离线页面 . 这是显示离线页面的正确方法,还是应该显示演示页面,然后在该页面中如果没有互联网连接,那么将数据保存到索引数据库?另外我有一个问题,当有互联网连接时,我想检查IndexDB中是否有任何数据,然后是否有数据上传到服务器 . 我应该在哪个事件中处理Activate或Fetch?

谢谢,
Jollyguy

1 回答

  • 0

    我有一个类似的问题,因为在我的服务工作者的早期版本中,我缓存了我的 index.html . 从服务工作者中删除它后,它仍然被缓存并且即使在离线时也继续加载 . 在你的情况下,我怀疑'/'被缓存,但'/demo.html'并不能解释你所看到的行为 .

    chrome dev工具的分辨率是:

    • 应用程序>服务工作者>检查'Update on reload'然后刷新页面或

    • 应用程序>清除存储>保持所有选中并单击'Clear selected'

相关问题