Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

javascript - Unregistering/Removing a Service 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...