未触发Service Worker提取事件

时间:2019-03-19 19:49:36

标签: javascript fetch service-worker

      self.addEventListener('install', function (event) {
    console.log('SW Installed');
    event.waitUntil(
      caches.open('static')
        .then(function (cache) {
          cache.addAll([
            '/',
            '/static/js/renderjson.js',
            "/static/css/app.css",
            '/static/js/contribute.js',
            "http://pending.biothings.io/denovodb/metadata",
            "http://pending.biothings.io/ccle/metadata",
            "http://pending.biothings.io/kaviar/metadata",
            "http://pending.biothings.io/biomuta/metadata",
            "http://pending.biothings.io/fire/metadata",
          ]);
        })
    );
  });

  self.addEventListener('activate', function () {
    console.log('SW Activated');
  });

  self.addEventListener('fetch', function(event) {
    console.log('FETCH',event.request);
    event.respondWith(
      caches.match(event.request)
        .then(function(response) {
          if (response) {
                // retrieve from cache
                console.log('Found ', event.request.url, ' in cache');
                return response;
            }

            // if not found in cache, return default offline content (only if this is a navigation request)
            if (event.request.mode === 'navigate') {
                return caches.match('/');
            }

            // fetch as normal
            console.log('Network request for ', event.request.url);
            return fetch(event.request);
        })
    );
  });

我是PWA的新手,所以请耐心等待,我正在运行龙卷风服务器,这里是注册信息:

if ('serviceWorker' in navigator) {
  // Use the window load event to keep the page load performant
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/static/js/worker.js');
    console.log('Service Worker registered');
  });
}

当我选中“应用程序”选项卡上的“脱机”框并刷新该应用程序无法脱机工作时,我放置了一些控制台日志以查看是否触发了获取事件,但似乎什么也没有发生。所有资产均已正确缓存,并验证它们是否存在。看起来最后一点只是使Worker服务器成为正确的缓存文件。

1 个答案:

答案 0 :(得分:0)

对于我来说,我们的网站只需要使用https即可使工作程序正常激活。这样做之后,听众就可以完美工作了。我建议您使用Workbox,方便得多!