JavaScript in the Background

Registering a Service Worker

Maximiliano Firtman

Maximiliano Firtman

Independent Consultant
JavaScript in the Background

Check out a free preview of the full JavaScript in the Background course

The "Registering a Service Worker" Lesson is part of the full, JavaScript in the Background course featured in this preview video. Here's what you'd learn in this lesson:

Maximiliano demonstrates the ability to execute code in a separate lifecycle by registering a service worker. A demonstration of accessing this separate lifecycle through the Chrome dev tools is also provided in this segment.


Transcript from the "Registering a Service Worker" Lesson

>> Okay, so we've covered the basics of what a service worker is, it's time to write it. So I will go back to my code. And actually, at the top of this file, I can start trying to register a service worker. So that's actually pretty simple. Its navigator.serviceWorker, be careful with capital W.register and the script URL, that's all.

Of course, I need to create that file, so that's fine. Shouldn't be in the scripts folder, by default, the service worker will take its scope at his current path. So if I create the service worker in the script sub folder, it will manage that folder and that folder only.

So that's why typically there are ways to bypass that, but it's get complicated without any reason. Most of the time, we want the service worker to be in the root folder of our web app. It can be the root folder of the origin, the domain or not. So, far it's empty.

So the only thing that I, it's just an empty file. I just need to specify here /sw.js, that will register that will install the service worker. Of course, right now the service worker is doing nothing. But just by doing this, just by registering a service worker, now we have the power to execute code in a separate lifecycle, in the background of our page, and I will show you that in action in a minute.

So, if I save this, I think both files are saved even if it's empty. So the only thing that I added is that line, navigator.serviceWorker.register, that's all. With that, I can go to any browser. Run this, and now how do I know if the service worker is running or not?

In Google Chrome, we can open that tools, and we are going to make usage of the Application tab. In fact, if we look at the Application tab, we have many options, and if we scroll down, we have a section for background services. So here we have a full section of the dev tools, prepare for background execution and read for the bargain background execution.

So I'm scrolling up again, here, if I get into service worker, it says that I do have a service worker activate it and stop and another one waiting for activation. So and here I have a link says, that says skip waiting. Actually, what it's doing is it's forcing the current service worker version.

We are not actually covering in this workshop the basics of service workers, so we are not covering what happens if you update the service worker and so on, so we are just gonna use that. Something that I will need to select here is this option, update on reload.

With this device login option set, what will happen is that every time you refresh your page, it will also refresh the service worker installation. So it will improve our work right now because we will be focusing on executing code in the background. So now if I refresh, you will see that now I have the service worker ID9.

Every time you refresh, it's reinstalling the service worker, even if it didn't change. So at this point, this is for debugging purposes, and it will force your last version of the service worker which will actually be there for you. But now, if you go to the console, if you write some code here, that code is running the main thread.

But there is a selector here that says stop, if you click that selector, you will see another, Scope that is the service worker. So from here, you can actually execute code, and now you are in the ServiceworkerGlobalScope. Even if it's an empty file, now I have a scope, so actually I can run code there.

The problem is that if I close my tab, I don't have Dev Tools, okay? Okay, I don't have a way to continue to execute going that background process. So if you want to actually play with this with a nature button, I can show you how. You can go back to that Chrome service worker internals website.

Fine, your service worker is this one on the current origin. From here, you can click inspect, and that will open a new window inspecting all your service worker. So now I can close my tab. So I don't have a tab anymore. I don't have a window anymore by still have code that is running in the background.

Can I do alert? No, I don't have UI, I don't have a DOM, I don't have user interface. And after a few seconds of inactivity, I will be dead. I'm the third service work. But here you can see I don't have the website anymore and the service worker is still running, and I have a console.

I can execute code there and if I have some code there that is doing an operation, it would wait for me, not forever, but it will wait for me. How much time will wait? It's unclear, so the spec doesn't say anything about that. So it depends on the browser, actually, okay?

In fact, probably if I try this again. No, it's still there. It's still up and running. Of course, here I can see if it's still running or not. It's still running, so I have a thread of my own service, that runs not matter if I do have my web app running or not.

That's kind of idea, okay? You have any questions at this point? Yeah.
>> Just maybe a clarification. Does you're running commands in the console here, keep the service worker going at all, or is it?
>> No after a while. So look at this, I can click here stop, and if I hit stop, so now it's stop, my depth tools now is disconnected, okay?

I force that but actually, if that happens, because of the browser's internal algorithm, you will see that while the Dev Tools is open. Well, Safari. Safari, it's kind of tricky, well, it's Safari, right? But if I'm running the app, for example, here In the Develop menu there is a whole menu for service workers.

So if you open the inspector, you won't find service workers there. You need to open here the service worker in localhost, that's my origin, and now I will have an inspector running in the service worker global scope. The problem is that if I close the window, that scope will last 5 to 10 seconds only because Safari's lifespan for the service worker is actually really short.

So it will kill my service worker pretty quickly. Okay, so that was registering the service worker. The problem is that it's doing nothing so far, but that's actually the home for most of the code that we will write, after this section, so everything will happen there. Because it has its own lifecycle, it doesn't matter if you close the tab.

You can still execute code in that context in the service worker global scope, okay? Make sense? Now going back to to Chrome. If I open my app again, in the application tab, In background services, you have one section per app. So you can see here. What's going on in the background?

What's the idea if my service worker wakes up, during the night, and is doing something with some of those APIs. I will be able to see that here if I record the activity. So I can open the inspector, record the activity, and wait. Meanings are worth wherever, and they will see every event here, and also I can, of course use a console and see what the service worker was doing in the console.

We will see this in action later. And within the service worker section, we also have a place here, it's probably from push to periodic sync, to actually test the push API, the background sync API, and the periodic background sync API, okay? So these are the tools that we will be using in the next few hours.

Unfortunately, Safari has no debugging tools like this, and on Firefox, it's kind of also for service workers, not so good. Also, Firefox is not supporting background sync or the others. But for push, for example on Safari or Firefox, you don't have any debugging tools. So you actually need to test that, and we will do that later directly with the URL code.

With chrome, we can test what happens. So what's the idea? For example, if I hit here push, this is going to simulate that the server is sending out, sending us that message. So if I hit here, nothing happens, but that's because my service worker is doing nothing with a push.

But without even explaining the API yet If I go to my service worker and I add an event listener to the sales object to the push event. Actually, we can send a message to the console, we have received a pollution message. Now, because I have just change, the service worker file, it's important to have that setting up, they don't reload.

So if I reload the page, I want to make sure that my new service worker, it's actually ready Because if not it will take the previous version by default. Make sense? This is just to show you the debugging tools quickly so for example I can go here to notifications will actually push my session maybe I can start recording.

But have in mind this is a simulator only, not the real push server. And if I refresh, I can try to push a message. And in the console, you can see that I've received the message. Of course, you can use any tool, so you can use our old friend debugger here, okay?

And you can try just again, send another message, like from Frontend Masters push, okay? And now, my debugger stopped there in the serviceWorker and I can actually see what's inside the push event. And I can see there is data, okay? Target blah, blah, blah blah. And the data will contain the message that we received.

We will work with this later. But I wanna show you how this actually works. You have a Service Worker and the Service Worker will have a lot of event listeners listening for each of the use cases for background execution.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now