Home > Articles

This chapter is from the book

This chapter is from the book

Registering a Service Worker

Web apps follow a specific process to install a service worker; there’s no automatic way to do it today. The app basically executes some JavaScript code to register the service worker with the browser. In the Tip Calculator app in Chapter 1, “Introducing Progressive Web Apps,” I added the code to do this directly in the app’s index.html file. For the PWA News app, we use a different approach.

In this section, you’ll modify the project’s existing public/index.html file plus add two JavaScript files: public/js/sw-reg.js and public/sw.js.

In the <head> section of the project’s public/index.html file, add the following code:

<!-- Register the service worker -->
<script src='js/sw-reg.js'></script>

This tells the web app to load a JavaScript file that registers the service worker for us. Next, let’s create that file. Create a new file called public/js/sw-reg.js and populate the file with the code shown in Listing 3.2.

Listing 3.2 PWA News sw-reg.js File

// does the browser support service workers?
if ('serviceWorker' in navigator) {
  // then register our service worker
  navigator.serviceWorker.register('/sw.js')
    .then(reg => {
      // display a success message
      console.log(`Service Worker Registration (Scope: ${reg.scope})`);
    })
    .catch(error => {
      // display an error message
      let msg = `Service Worker Error (${error})`;
      console.error(msg);
      // display a warning dialog (using Sweet Alert 2)
      Swal.fire('', msg, 'error');
    });
} else {
  // happens when the app isn't served over a TLS connection (HTTPS)
  // or if the browser doesn't support service workers
  console.warn('Service Worker not available');
}

The code here isn’t very complicated; it all centers around the call to navigator.serviceWorker.register. The code first checks to see if the serviceWorker object exists in the browser’s navigator object. If it does, then this browser supports service workers. After the code verifies it can register the service worker, it does so through the call to navigator.serviceWorker.register.

The register method returns a promise, so the code includes then and catch methods to act depending on whether the installation succeeded or failed. If it succeeds, it tosses a simple message out to the console. If the call to register fails (caught with the catch method), we warn the user with an alert dialog.

Two potential error conditions exist here: if the browser doesn’t support service workers and if service worker registration fails. When the browser doesn’t support service workers, I log a simple warning to the console (using console.warn). I don’t do anything special to warn the user because this is progressive enhancement, right? If the browser doesn’t support service workers, the user just continues to use the app as is, with no special capabilities provided through service workers.

On the other hand, if registration fails, then the code is broken (because we already know the browser supports service workers), and I want to let you know more obnoxiously with an alert dialog. I did this because you’re learning how this works, and I wanted the error condition to be easily recognized. I probably wouldn’t do this for production apps because if the service worker doesn’t register, the app simply falls back to the normal mode of operation.

Service workers don’t start working until the next page loads anyway, so to keep things clean, you can defer registering the service worker until the app finishes loading, as shown in Listing 3.3.

Listing 3.3 PWA News sw-reg.js File (Alternate Version)

// does the browser support service workers?
if ('serviceWorker' in navigator) {
  // Defer service worker installation until the page completes loading
  window.addEventListener('load', () => {
    // then register our service worker
    navigator.serviceWorker.register('/sw.js')
      .then(reg => {
        // display a success message
        console.log(`Service Worker Registration (Scope: ${reg.scope})`);
      })
      .catch(error) => {
        // display an error message
        let msg = `Service Worker Error (${error})`;
        console.error(msg);
        // display a warning dialog (using Sweet Alert 2)
        Swal.fire('', msg, 'error');
      });
  })
} else {
    // happens when the app isn't served over a TLS connection (HTTPS)
    // or if the browser doesn't support service workers
    console.warn('Service Worker not available');
}

In this example, the code adds an event listener for the load event and starts service worker registration after that event fires. All this does is defer the additional work until the app is done with all its other startup stuff and shouldn’t even be noticeable to the user.

Next, let’s create a service worker. Create a new file called public/sw.js and populate it with the code shown in Listing 3.4. Notice that we created the service worker registration file in the project’s public/js/ folder, but this one goes into the web app’s root folder (public/); I’ll explain why in “Service Worker Scope” later in this chapter—I’m just mentioning it now to save you a potential problem later if you put it in the wrong place.

Listing 3.4 First Service Worker Example: sw-34.js

self.addEventListener('fetch', event => {
  // fires whenever the app requests a resource (file or data)
  console.log(`SW: Fetching ${event.request.url}`);
});

This code is simple as well. All it does is create an event listener for the browser’s fetch event, then logs the requested resource to the console. The fetch event fires whenever the browser, or an app running in the browser, requests an external resource (such as a file or data). This is different from the JavaScript fetch method, which enables an app’s JavaScript code to request data or resources from the network. The browser requesting resources (such as a JavaScript or image file referenced in an HTML script or img tag) and a web app’s JavaScript code requesting a resource using the fetch method will both cause the fetch event to fire.

This is the core functionality of a service worker, intercepting fetch events and doing something with the request—such as getting the requested resource from the network, pulling the requested file from cache, or even sending something completely different to the app requesting the resource. It’s all up to you: your service worker delivers as much or as little enhancement as needed for your app.

With this file in place, refresh the app in the browser and watch what happens. Nothing, right? There’s not much to see here since, everything happens under the covers. In this example, the service worker does nothing except log the event; as you can see in the browser, the app loaded as expected, so the app’s still working the same as it did before.

Open the browser’s developer tools and look for a tab labeled Application (or something similar) and a side tab labeled Service Workers. If you did everything right, you should see your service worker properly registered in the browser, as shown in Figure 3.5 (in Google Chrome).

FIGURE 3.5

Figure 3.5 Chrome Developer Tools Application Tab

If the browser can’t register the service worker, it displays error messages in this panel to let you know.

In the latest Chrome browser and the Chromium-based Edge browser, you can also open a special page that displays information about all service workers registered in the browser. Open the browser and enter the following value in the address bar:

chrome://serviceworker-internals/

The browser opens the page shown in Figure 3.6, listing all registered service workers.

FIGURE 3.6

Figure 3.6 Chrome Service Worker Internals Page

The one thing missing from the service worker as it stands today is for it to actually do something with the fetch request. Listing 3.5 adds an additional line of code to our existing service worker:

event.respondWith(fetch(event.request));

This code instructs the browser to go ahead and get the requested file from the network. Without this statement in the event listener, the browser was doing this anyway. Since the event listener didn’t act on the request and return a promise telling the browser it was dealing with it, then the browser goes ahead and gets the file anyway. That’s why the app works without this line. Adding the line just completes the event listener.

Listing 3.5 Second Service Worker Example: sw-35.js

self.addEventListener('fetch', event => {
  // fires whenever the app requests a resource (file or data)
  console.log(`SW: Fetching ${event.request.url}`);
  // next, go get the requested resource from the network,
  // nothing fancy going on here.
  event.respondWith(fetch(event.request));
});

The browser passes the fetch event listener an event object service workers query to determine which resource was requested. Service workers use this mechanism to determine whether to get the resource from cache or request it from the network. I cover this in more detail later (in this chapter and the next), but for now this extra line of code simply enforces what we’ve already seen the browser do—get the requested resource from the network.

The browser fires two other events of interest to the service worker developer: install and activate. Listing 3.6 shows a service worker with event listeners for both included.

Listing 3.6 Third Service Worker Example: sw-36.js

self.addEventListener('install', event => {
  // fires when the browser installs the app
  // here we're just logging the event and the contents
  // of the object passed to the event. the purpose of this event
  // is to give the service worker a place to setup the local
  // environment after the installation completes.
  console.log(`SW: Event fired: ${event.type}`);
  console.dir(event);
});

self.addEventListener('activate', event => {
  // fires after the service worker completes its installation.
  // It's a place for the service worker to clean up from
  // previous service worker versions.
  console.log(`SW: Event fired: ${event.type}`);
  console.dir(event);
});

self.addEventListener('fetch', event => {
  // fires whenever the app requests a resource (file or data)
  console.log(`SW: Fetching ${event.request.url}`);
  // next, go get the requested resource from the network,
  // nothing fancy going on here.
  event.respondWith(fetch(event.request));
});

The browser fires the install event when it completes installation of the service worker. The event provides the app with an opportunity to do the setup work required by the service worker. At this point, the service worker is installed but not yet operational (it doesn’t do anything yet).

The browser fires the activate event when the current service worker becomes the active service worker for the app. A service worker works at the browser level, not the app level, so when the browser installs it, it doesn’t become active until the app reloads in all browser tabs running the app. Once it activates, it stays active for any browser tabs running the app until the browser closes all tabs for the app or the browser restarts.

The activate event provides service workers with an opportunity to perform tasks when the service worker becomes the active service worker. Usually, this means cleaning up any cached data from a previous version of the app (or service worker). You’ll learn a lot more about this in Chapter 4, “Resource Caching”; for now, let’s add this code to our existing service worker and see what happens.

Once you’ve updated the code, reload the page in the browser, then open the developer tools console panel and look for the output shown in Figure 3.7. Chances are, you won’t see it—that’s because the previous version of the service worker is still active. You should see the install event fire but not the activate event.

FIGURE 3.7

Figure 3.7 Chrome Browser Tools Console Pane with Installation Output

You have several options for activating this new service worker. I explain two here and cover programmatic options in “The Service Worker Lifecycle” later in the chapter. One option is to close and reopen the browser, then reload the app; this automatically enables the registered service worker.

Another option is to configure the browser developer tools to automatically activate the new service worker once it registers the service worker; this approach is useful only when debugging or testing a PWA. At the top of the service workers pane shown in Figure 3.5 is a checkbox labeled Update on reload; when you enable (check) this checkbox, the browser automatically updates and activates new service workers every time you reload the page with a new service worker.

Force the browser to activate the new service worker, then look at the console page. You should now see the output shown in Figure 3.8 with each network request logged to the console.

FIGURE 3.8

Figure 3.8 Chrome Browser Tools Console Pane with Service Worker Output

At this point, the app has a functioning service worker listening for all relevant events and fetching all requested resources from the network. In the next sections, we talk about service worker scope (as promised) and the service worker lifecycle; then I’ll show you more you can do with service workers.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020