Playing Hide & Seek With My Service Worker Instance!

If you are working with Service Workers for the first time you'll probably have noticed that the Service Worker's functionality can be found on different objects. This can be a little bit confusing.

In diesem Artikel:

First of all the API is a little bit misleading because navigator.serviceWorker is not an instance of the Service Worker itself – it’s only a container. The Service Worker itself is provided by the property controller of this ServiceWorkerContainer.
  • navigator.serviceWorkerServiceWorkerContainer
  • navigator.serviceWorker.controllerServiceWorker
And there’s also the ServiceWorkerRegistration that’s not accessible as a property but can be accessed by different methods. Let’s start with the ServiceWorkerContainer! It allows you to access the current Service Worker and also allows you to receive messages from it in your application.
				
					navigator.serviceWorker.addEventListener('message', event => {
    console.log('Message from service worker received: ', event.data);
});
				
			

The ServiceWorkerContainer also allows you to register a new Service Worker. The register() method responds with a promise that resolves with a ServiceWorkerRegistration object if the registration was successful. If there’s already a registered Service Worker you will get the current ServiceWorkerRegistration – otherwise a new one.

				
					navigator.serviceWorker.register('serviceWorker.js', registration => {
    console.log('Service worker successfully registered');
});

				
			

The ServiceWorkerRegistration represents – as the name reads – the registration of the Service Worker. Besides the register()-method this registration can also be accessed in other ways:

  • navigator.serviceWorker.ready(): The returning promise of this method will never be rejected and waits until the Service Worker is ready.
  • navigator.serviceWorker.getRegistration(scope): Returns a promise that resolves with the Service Worker registration of your specific scope (usually given as relative url but also optional). If no registration is available the promise resolves with undefined.
  • navigator.serviceWorker.getRegistrations(): Returns a promise that resolves with an array of all active Service Worker registrations. If there’s no active registration the promise will resolve with an empty array.

The serviceWorkerRegistration allows you to access several APIs and functions you can use to improve your web application (only a few examples):

On the registration.active-property you have access to the active Service Worker. This is an instance of the ServiceWorker-interface. This object is the instance that controls your site and also your network requests. If a Service Worker is registered for the first time it won’t control your site instantly and a reload of the page is necessary.

The active Service Worker is also accessible with window.navigator.controller but be careful! If you force a page reload this property is null. The property will also be null if there’s no active Service Worker – registration.active is still available and gives you the last value set as active Service Worker. But why do you need your active Service Worker? The Service Worker is necessary if you want to send messages to your Service Worker instance and communicate with your Service Worker.

				
					navigator.serviceWorker.controller.postMessage(data);
				
			

Also you can watch state changes of the Service Worker on its instance.

				
					navigator.serviceWorker.controller.onstatechange = event => {
    const serviceWorker = navigator.serviceWorker.controller;
    console.log('Current service worker state: ', serviceWorker.state);
};
				
			

As you see there are different ways to access your Service Worker functionality and the naming isn’t clear all the time. The Service Worker specification is still a draft at W3C and so it maybe changes and becomes more clear when the specification is finished. I hope I was able to bring a little light into the darkness and it is a little bit clearer now.

Stay tuned and have fun. 🙂

Mehr Artikel zu JavaScript, PWA
Kostenloser
Newsletter

Aktuelle Artikel, Screencasts, Webinare und Interviews unserer Experten für Sie

Verpassen Sie keine Inhalte zu Angular, .NET Core, Blazor, Azure und Kubernetes und melden Sie sich zu unserem kostenlosen monatlichen Dev-Newsletter an.

Newsletter Anmeldung
Diese Artikel könnten Sie interessieren
Low-angle photography of metal structure
AI
cl-neu

AI-Funktionen zu Angular-Apps hinzufügen: lokal und offlinefähig

Künstliche Intelligenz (KI) ist spätestens seit der Veröffentlichung von ChatGPT in aller Munde. Wit WebLLM können Sie einen KI-Chatbot in Ihre eigenen Angular-Anwendungen integrieren. Wie das funktioniert und welche Vor- und Nachteile WebLLM hat, lesen Sie hier.
26.02.2024
.NET
cl-neu

Adding Superpowers to your Blazor WebAssembly App with Project Fugu APIs

Blazor WebAssembly is a powerful framework for building web applications that run on the client-side. With Project Fugu APIs, you can extend the capabilities of these apps to access new device features and provide an enhanced user experience. In this article, learn about the benefits of using Project Fugu APIs, the wrapper packages that are available for Blazor WebAssembly, and how to use them in your application.

Whether you're a seasoned Blazor developer or just getting started, this article will help you add superpowers to your Blazor WebAssembly app.
28.02.2023
Angular
MS-rund

Implementing Smart and Presentational Components with Angular: Condensed Angular Experiences – Part 4

In this article, we will explore how to apply the concept of smart and presentational components with Angular. We will choose a complex-enough target to see all aspects in action, yet understandable and within the scope of this article. The goal is to teach you how to use this architecture in your way. For that, we will iterate through different development stages, starting with the target selection and implementing it in a naive way. After the first development, we will refactor that naive solution into smart and presentational components that are reusable, refactor-friendly, and testable.
23.01.2023
Angular
MS-rund

About Smart and Presentational Components, Architecture Overview & Concepts: Condensed Angular Experiences – Part 3

Modern web technologies enable us to write huge business applications that are performant and easy to use. But with time comes complexity to our projects naturally. That added complexity sums up and makes further app development slow and cumbersome. This article discusses how a simple architectural concept can make every app more maintainable, faster to develop, and extendable in the long run.
08.04.2022
Project Fugu
cl-neu

Dark Mode Support – Real-World PWA: The Making Of Paint.Js.Org – Part 5

In part five of the series about the making of the web-based Microsoft Paint clone paint.js.org, I want to show how to implement support for dark mode in your web applications.
20.05.2021
Project Fugu
cl-neu

Accessing Files & File Handler – Real-World PWA: The Making Of Paint.Js.Org – Part 4

In this fourth part of the series about the Microsoft Paint remake on paint.js.org, I want to demonstrate how you can save your drawings to your local disk, read them back later and how to add your web app as a handler for certain file extensions.
12.05.2021