Unregistering/Removing a Service Worker

孤人 提交于 2019-12-01 12:21:12

I stumbled across this answer which seemed a better-than-most solution.

Blog Post: https://medium.com/@nekrtemplar/self-destroying-serviceworker-73d62921d717

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

It destroys itself with this code:

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))
    });
});

Here's an even more in-depth explanation and further improvement on the above code. https://love2dev.com/blog/how-to-uninstall-a-service-worker/

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(); }
            }
        });
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!