The answer is that you first use the getRegistrations method to return a Promise which resolves to an array of ServiceWorkerRegistration objects:
var regs=await navigator.serviceWorker. getRegistrations();
Next you scan though the array to find the Service Worker you want to remove, either by scope or by state say. You then use the unregister method of that ServiceWorkerRegistration object.
For example to remove all Service Workers you would use:
async function remove() {
var regs = await navigator.serviceWorker. getRegistrations();
for (let reg of regs) {
reg.unregister();
}
}
Browsers also provide ways to manage Service Workers. For example, Chrome has an Application tab which can be used to monitor and stop Service Workers. You can also select different behaviors which are useful in testing. For example you can simulate offline working:
Also notice that you can examine and manage the cache.
The Future Of Service Workers
In this chapter we have only touched on the basic use of Service Workers. In addition to acting as a proxy for resource requests, there are also interfaces for implementing periodic synchronization and push notifications. In short, Service Workers offer opportunities that are difficult to realize any other way. Many think that modern JavaScript, HTML and CSS plus new APIs such as Service Workers and those that are related will allow the web to develop in new ways and make web apps as good as desktop apps.
At the time of writing it is estimated that over 94% of users have a browser that supports Service Workers. Many large companies have decided that this is enough to make it worth the trouble to implement Service workers – Google, Twitter, FaceBook, Bloomberg and You Tube.
It does look as if Service Workers are the future of the web.
Summary
New JavaScript APIs tend to use Promises and this means they are best used with async and await.
The Fetch and Cache APIs are two good examples and these are fundamental to using the new Service Worker.
The Fetch API is a modern implementation of the XMLHttpRequest and it can be used to download almost any file the browser has access to, and to send data to the server using Get or Post.
The Fetch API uses Request and Response objects to specify the resource location and represent the response.
The cache API is a replacement for appCache.
The CacheStorage object stores a set of Cache objects each of which stores a set of key value pairs.
A Service Worker is associated with a scope – a range of URLs – and once installed it is active whenever the browser loads a URL in the scope.
The Service Worker intercepts all URLs in its scope via the Fetch event.
The Service Worker can return a Response object which has been retrieved from a Cache object or it can construct a Response object from scratch. It acts as a proxy server and enables an app to function offline as well as online.