注销/删除服务辅助角色



我有一个不再更新的糟糕的服务工作者。我首先注意到了Chrome中的问题。然后,我将以下代码放在 index.html 文件和 sw.js(服务工作进程(文件中。在大多数情况下,它似乎工作正常。Firefox 似乎是唯一没有删除服务工作者的浏览器。我使用下面的文章创建了取消注册脚本。

如何卸载服务辅助角色?

我也使用了这篇文章和代码,并得到了相同的结果。

如何删除有缺陷的服务工作线程,或实施"终止开关"?

我还收到一条错误消息,getRegistrations()说它未定义。也不知道如何解决这个问题。

对这两个问题的帮助将不胜感激。

<script>
navigator.serviceWorker.getRegistrations().then(function(registrations) {
 for(let registration of registrations) {
  registration.unregister();
} });</script>

下面的示例代码将检查在浏览器中注册的服务工作者并获取它。

registration.active.scriptURL 将为您提供所有服务工作线程的确切 URL。

registration.unregister((; 将删除该服务工作线程。

链接: https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/unregister

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.getRegistrations()
        .then(function(registrations) {
            for(let registration of registrations) {
               if(registration.active.scriptURL == 'http://localhost/my-push/myworker.js'){ registration.unregister(); }
            }
        });
}

如果要更新服务工作进程代码,请使用 https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/update

我偶然发现了这个答案,这似乎是一个比大多数解决方案更好的答案。

博客文章: https://medium.com/@nekrtemplar/self-destroying-serviceworker-73d62921d717

Github: https://github.com/NekR/self-destroying-sw

它使用以下代码销毁自己:

self.addEventListener('install', function(e) {
  self.skipWaiting();
});
self.addEventListener('activate', function(e) {
  self.registration.unregister()
    .then(function() {
      return self.clients.matchAll();
    })
    .then(function(clients) {
      clients.forEach(client => client.navigate(client.url))
    });
});

这是对上述代码的更深入的解释和进一步改进。https://love2dev.com/blog/how-to-uninstall-a-service-worker/

最新更新