Unregistering/Removing a Service Worker

Rai*_*nJ9 3 html javascript service firefox worker

I have a bad service worker that is no longer updating. I noticed the issue in Chrome first. I then put the following code in the index.html file and in the sw.js (service worker) file. For the most part it seems to be working fine. Firefox seems to be the only browser that is not removing the service worker. I used the article below to create the unregister script.

How do I uninstall a Service Worker?

I have also used this article and code and got the same results.

How can I remove a buggy service worker, or implement a "kill switch"?

I am also receiving an error message for getRegistrations() saying it is undefined. Not sure how to fix that either.

Help with both of these issues would be greatly appreciated.

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

Akh*_*mar 5

Below sample code will check for service worker registered in your browser and fetch it.

registration.active.scriptURL will provide you exact url of all service workers.

registration.unregister(); will remove that service worker.

LINK: 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(); }
            }
        });
}
Run Code Online (Sandbox Code Playgroud)

If you want to update service worker code than use https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/update


nar*_*fie 4

我偶然发现了这个答案,它似乎比大多数解决方案都要好。

博客文章: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))
    });
});
Run Code Online (Sandbox Code Playgroud)

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