【问题标题】:Offline page is not showing in fetch function when using service worker?使用服务人员时,离线页面未显示在提取功能中?
【发布时间】:2016-05-11 20:13:36
【问题描述】:

一天前我才刚刚开始了解 Service Worker。根据我的学习,我想创建一个离线应用程序。我创建了 2 个页面,即 demo.htmloffline.html。我的目标是在没有互联网连接时,我必须显示offline.html。

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

现在我没有刷新,而是将 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) {
}

根据我对 Service Worker 的了解,如果没有互联网连接,在 fetch 功能中,我可以显示离线页面。这是显示离线页面的正确方法,还是应该显示演示页面,然后在没有互联网连接的情况下在该页面中显示,然后将数据保存到索引数据库?另外我有一个问题,当有互联网连接时,我想检查 IndexDB 中是否有任何数据,然后将数据上传到服务器。我应该在哪种情况下处理 Activate 或 Fetch?

谢谢,
小伙子

【问题讨论】:

  • 嗨@Jollyguy 你解决了吗?我对此也很陌生。

标签: service-worker


【解决方案1】:

我遇到了类似的问题,这是因为在我的 Service Worker 的早期版本中,我缓存了我的 index.html。从 service worker 中删除它后,它仍然被缓存并且即使在离线时也继续加载。在您的情况下,我怀疑“/”已被缓存,但“/demo.html”并不能解释您所看到的行为。

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

  1. 应用程序>服务工作者>检查“重新加载时更新”然后刷新页面 或
  2. 应用程序 > 清除存储 > 保持全部选中并单击“清除选中”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-02
    • 2017-04-17
    • 2017-01-18
    • 2018-10-28
    • 2022-10-20
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    相关资源
    最近更新 更多