简体   繁体   English

服务工作人员在脱机时未注册

[英]Service worker unregistered when offline

So I've created and successfully registered a Service Worker when the browser is online. 所以我在浏览器在线时创建并成功注册了Service Worker。 I can see that the resources are properly cached using the DevTools. 我可以看到使用DevTools正确缓存了资源。 The issue is when I switch to offline mode, the service worker seems to unregister itself and, as such, nothing but the google chrome offline page is displayed. 问题是当我切换到离线模式时,服务工作者似乎取消注册自己,因此,只显示谷歌浏览器离线页面。

The code. 编码。

'use strict';
var CACHE_NAME = 'v1';
var urlsToCache = [
  '/'
];

self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }

        // IMPORTANT: Clone the request. A request is a stream and
        // can only be consumed once. Since we are consuming this
        // once by cache and once by the browser for fetch, we need
        // to clone the response.
        var fetchRequest = event.request.clone();

        return fetch(fetchRequest).then(
          function(response) {
            // Check if we received a valid response
            if(!response || response.status !== 200 || response.type !== 'basic') {
              return response;
            }

            // IMPORTANT: Clone the response. A response is a stream
            // and because we want the browser to consume the response
            // as well as the cache consuming the response, we need
            // to clone it so we have two streams.
            var responseToCache = response.clone();

            caches.open(CACHE_NAME)
              .then(function(cache) {
                cache.put(event.request, responseToCache);
              });

            return response;
          }
        );
      })
    );
});

And the test script, if that helps. 测试脚本,如果有帮助的话。

'use strict';
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(function(registration) {
    // Registration was successful
    console.log('ServiceWorker registration successful with scope: ', registration.scope);

    var serviceWorker;
    if (registration.installing) {
      serviceWorker = registration.installing;
    } else if (registration.waiting) {
      serviceWorker = registration.waiting;
    } else if (registration.active) {
      serviceWorker = registration.active;
    }

    if (serviceWorker) {
      console.log('ServiceWorker phase:', serviceWorker.state);

      serviceWorker.addEventListener('statechange', function (e) {
        console.log('ServiceWorker phase:', e.target.state);
      });
    }
  }).catch(function(err) {
    // registration failed :(
    console.log('ServiceWorker registration failed: ', err);
  });
}

Edit: Checking the console I've found this error. 编辑:检查控制台我发现了这个错误。 sw.js:1 An unknown error occurred when fetching the script.

Aslo, as per a suggestion, I've added this code yet the problem persists. Aslo,根据建议,我已添加此代码但问题仍然存在。

this.addEventListener('activate', function(event) {
  var cacheWhitelist = ['v2'];

  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});

it seems you haven't added any activate event which meant to render cached elements when available. 似乎你没有添加任何激活事件,这意味着在可用时呈现缓存元素。 Hope the code help you. 希望代码能帮到你。

self.addEventListener('activate', function(e) {
    /*service worker activated */
    e.waitUntil(
      caches.key().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if(key){
          //remove old cache stuffs
          return caches.delete(key);
        }
       }));
      })
    );
 });

The problem appears to have fixed itself. 问题似乎已经解决了。 To anyone here from google, try restarting the browser. 对于谷歌的任何人,请尝试重新启动浏览器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM