ServiceWorker is more and more often used in websites development. It’s being added to popular tools and libraries. Sometimes, it might be used unintentionally (generated by a pre-configured tool automatically) or for experimental purposes. This leads to a situation where ServiceWorker needs to be removed.
Is it easy to remove ServiceWorker from a website?
tl;dr: Yes, but it’s not easy to find out how to do it right. ServiceWorker is a relatively new technology with a complicated API, even seasoned developers might find it challenging to get their heads around it.
There are numerous answers on the internet about how to remove ServiceWorker from a website, but in most cases effect of that removal won’t be applied to the users on the next visit of the website.
A couple of days ago, I returned to a website I was using a couple weeks ago. The website was working, showing the header and the sidebar, but no content. Content area was white. The reason to that was a broken ServiceWorker, and a failure to remove it. Following snippet was used:
This snippet from StackOverflow answer is the first link on google when searching “how to remove service worker”. There are also other SO answers which link to that one.
The problem here is that ServiceWorker, unregistered this way, isn’t going away immediately. It continues controlling already opened pages and won’t release them until they all are reloaded or closed. Only then, finally, ServiceWorker is being physically removed the website.
This is might be a frustrating experience for your users
Unregistering ServiceWorker properly
To do it properly, as special ServiceWorker has to be constructed. It has to be put in the place of the previous broken/unwanted ServiceWorker, with the same name. Any previous registration or unregistration code has to be removed from the codebase (i.e. from the pages’ scripts).
Such ServiceWorker can be found here, in the Self-destroying ServiceWorker repo.
And… That’s it. After the next deploy of the website, everyone who is visiting your website will get the self-destroying ServiceWorker, which will unregister itself for real, as soon as the script is downloaded.
Note: If the previous ServiceWorker file was cached with HTTP headers, the update may take some time depending on how long the caching duration is set, but not more than 24 hours.