How do I uninstall a Service Worker?

HtmlGoogle ChromeService Worker

Html Problem Overview


After deleting /serviceworker.js from my root directory, Chrome still runs the service worker that I removed from my webroot. How do I uninstall the service worker from my website and Chrome so I can log back into my website?

I've tracked the issue down to Service Work's cache mechanism and I just want to remove for now until I have time to debug it. The login script that I'm using redirects to Google's servers for them to login to their Google account. But all I get from the login.php page is an ERR_FAILED message.

Html Solutions


Solution 1 - Html

Removing Service Workers Programmatically

You can remove service workers programmatically like this:

navigator.serviceWorker.getRegistrations().then(function(registrations) {
 for(let registration of registrations) {
  registration.unregister()
} })

Docs: getRegistrations, unregister

Removing Service Workers Through The User Interface

You can also remove service workers under the Application tab in Chrome Devtools.

Solution 2 - Html

You can also go to the URL: chrome://serviceworker-internals/ and unregister a serviceworker from there.

Solution 3 - Html

You can do this through Chrome Developer Tool as well as Programatically.

  1. Find all running instance or service worker by typing

> chrome://serviceworker-internals/

in a new tab and then select the serviceworker you want to unregister.

  1. Open Developer Tools (F12) and Select Application. Then Either

> Select Clear Storage -> Unregister service worker

or

> Select Service Workers -> Choose Update on Reload

  1. Programatically

if(window.navigator && navigator.serviceWorker) {
  navigator.serviceWorker.getRegistrations()
  .then(function(registrations) {
    for(let registration of registrations) {
      registration.unregister();
    }
  });
}

Solution 4 - Html

In Google Chrome, you can go to Developer tools (F12) -> Application -> Service worker and unregister the service workers from the list for that specific domain.

Screenshot

This method is effective in development mode of a site and mostly they run on localhost which is you may need for other project's development.

Solution 5 - Html

FYI, in case you are using MacOS Safari browser, there is one way to forcibly unregister a service worker (steps and images for Safari 12.1):

  1. Safari > Preferences... > Privacy > Manage Website Data… Safari Preferences : Privacy

  2. Enter domain name (ex. 'localhost'), click "Remove" Safari Preferences : Privacy : manage website data

Note: In addition to service workers, this also will erase all caches, cookies, and databases for this domain.

Solution 6 - Html

You should detecte two API in your devices: getRegistrations and getRegistration. The service-worker not has a unique set of APIs in all platforms. For example, some browsers only have a navigator.serviceWorker.getRegistration, no navigator.serviceWorker.getRegistrations. So you should consider with both.

Solution 7 - Html

In addition to the already correct answers given, if you want also to delete the SW cache you can invoke the following method:

if ('caches' in window) {
    caches.keys()
      .then(function(keyList) {
          return Promise.all(keyList.map(function(key) {
              return caches.delete(key);
          }));
      })
}


More in this article (Paragraph: "Unregister a service worker")


Another possibility, via Browser, is by accessing the "Cache Storage" section and click on the "Clear Site Data" button:

enter image description here

Solution 8 - Html

safely uninstall Service Worker

if ('serviceWorker' in navigator) {
      navigator.serviceWorker.getRegistrations().then(function (registrations) {
        for (const registration of registrations) {
          // unregister service worker
          console.log('serviceWorker unregistered');
          registration.unregister();
        }
      });
    }

Solution 9 - Html

to detect service worker:

navigator.serviceWorker.controller

Code to for deletion of service worker:

navigator.serviceWorker.getRegistrations()
  .then(registrations => {
    registrations.forEach(registration => {
      registration.unregister();
    })
  });

  navigator.serviceWorker.getRegistrations().then(function(registrations) {
   for(let registration of registrations) {
    registration.unregister()
  } })

  if(window.navigator && navigator.serviceWorker) {
    navigator.serviceWorker.getRegistrations()
    .then(function(registrations) {
      for(let registration of registrations) {
        registration.unregister();
      }
    });
  }

  if ('caches' in window) {
      caches.keys()
        .then(function(keyList) {
            return Promise.all(keyList.map(function(key) {
                return caches.delete(key);
            }));
        })
  }

  if ('serviceWorker' in navigator) {
        navigator.serviceWorker.getRegistrations().then(function (registrations) {
          for (const registration of registrations) {
            // unregister service worker
            console.log('serviceWorker unregistered');
            registration.unregister();

            setTimeout(function(){
              console.log('trying redirect do');
              window.location.replace(window.location.href); // because without redirecting, first time on page load: still service worker will be available
            }, 3000);
          }
        });
      }

Solution 10 - Html

IF your service worker don't let you update your files. You will need to replace serviceworker file (sw.js / ServiceWorker.js) with the next 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))
    });
});

Source here

Solution 11 - Html

It can also be done in Chrome through application tab: enter image description here

Solution 12 - Html

This code is compatible with Internet Explorer:

if (navigator.serviceWorker) {
    navigator.serviceWorker.getRegistrations().then(                
        function(registrations) {
            for (let idx in registrations) {
                registrations[idx].unregister()
            }
        })
}

IE doesn't support 'for...of' and 'for...of' construction may lead to "'SCRIPT1004: Expected ';'" error

Solution 13 - Html

The other answers all add code to the live website to remove the service worker. However I didn't want to leave that live code running forever so I developed a solution that works from within the service worker itself. The steps are below, I posted more detail and explanation on my blog.

  1. Delete the code that registers the service worker.
  2. Replace the service worker script with the following file. The new code must be available from the same URL the previous service worker was at. If you had multiple service worker URLs in the past you should duplicate the code at all of them.
console.log("Cleanup Service Worker Starting");

caches.keys()
	.then(keys =>
		Promise.all(
			keys.map(async key => console.log("caches.delete", key, await caches.delete(key)))))
	.then(async () => {
		console.log("registration.unregister", await registration.unregister());
	})
	.then(() => console.log("DONE"))
	.catch(console.error);

This code is fairly straight forward. First it deletes all the caches, then it unregisters itself.

Users' browsers will automatically check for an updated service worker the next time they load your website, or the next event 24h after the last service worker check. This means that existing users will run this cleanup on their next visit.

Solution 14 - Html

as for me , i just use a new nonexistent scope service worker to replace old one,

ServiceWorker: {
        events: true,
        // what range of URLs a service worker can control. Use a nonexistent path to disable ServiceWorker
        scope: '/disable-service-worker/',
      },

as for the app.js, i add below code to unregister old sw:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.getRegistrations().then(registrations => {
    for (const registration of registrations) {
      // keep only serviceWorker which scope is /disable-service-worker/, The purpose is to make serviceWorker useless
      if (registration.scope.includes('/disable-service-worker/') === false) {
        registration.unregister()
      }
    }
  });
  // clear cache of service worker
  caches.keys().then(keyList => {
    return Promise.all(
      keyList.map(key => {
        return caches.delete(key);
      }),
    );
  });
}

Solution 15 - Html

Open this page: chrome://serviceworker-internals and click to unregister button.

If you want to unregister all service worker open the developer tools and run this code on above page.

document.querySelectorAll("button.unregister").forEach(item=>{ item.click()})

Solution 16 - Html

Open in Chrome

chrome://serviceworker-internals/?devtools

then F12 in Console

$$('.unregister').forEach(b => b.click())

Solution 17 - Html

If You want to unregister all of the registered service workers in Browser, you can do it by opening ex.

  • Chrome: chrome://serviceworker-internals/
  • Brave brave://serviceworker-internals/

open DevTools > Console and paste this:

$$('.unregister').forEach(b => b.click())

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark TomlinView Question on Stackoverflow
Solution 1 - HtmlDaniel HerrView Answer on Stackoverflow
Solution 2 - Htmlk00kView Answer on Stackoverflow
Solution 3 - HtmlSakshi NagpalView Answer on Stackoverflow
Solution 4 - HtmlAsim K TView Answer on Stackoverflow
Solution 5 - HtmlterrymorseView Answer on Stackoverflow
Solution 6 - HtmlGuoXView Answer on Stackoverflow
Solution 7 - HtmlFrancescoView Answer on Stackoverflow
Solution 8 - HtmlPankaj RupaparaView Answer on Stackoverflow
Solution 9 - HtmlVitalijView Answer on Stackoverflow
Solution 10 - HtmlDaniel Jose Padilla PeñaView Answer on Stackoverflow
Solution 11 - HtmlMichael NellesView Answer on Stackoverflow
Solution 12 - HtmlSergey BeloglazovView Answer on Stackoverflow
Solution 13 - HtmlKevin CoxView Answer on Stackoverflow
Solution 14 - Htmldanny wangView Answer on Stackoverflow
Solution 15 - HtmlKadirView Answer on Stackoverflow
Solution 16 - HtmlValentin PetkovView Answer on Stackoverflow
Solution 17 - HtmldevzomView Answer on Stackoverflow