What is a Service Worker?

Ceyhun Keklik
Commencis
Published in
7 min readMar 16, 2018

Service Worker is a script that works on browser background without user interaction independently. Also, It resembles a proxy that works on the user side. With this script, you can track network traffic of the page, manage push notifications and develop “offline first” web applications with Cache API.

What can we do with Service Worker?

  • You can dominate Network Traffic!
    You can manage all network traffic of the page and do any manipulations.
    Is it really possible to dominate all network traffic? Yes! For example, when the page requests to a CSS file, you can send plain text as a response or when the page requests to an HTML file, you can send png file as a response. Of course, you can send true response too :)
  • You can “Cache”!
    You can cache any request/response pair with Service Worker and Cache API and you can access these offline content anytime.
  • You can manage Push Notifications!
    You can manage push notifications with Service Worker and show any information message to the user.
  • You can continue!
    Although Internet connection is broken, you can start any process with Background Sync of Service Worker.

What can’t we do with Service Worker?

  • You can’t access the window!
    You can’t access the window, therefore, You can’t any manipulation DOM elements. But, you can communicate to the window through postMessage and manage processes that you want.
  • You can’t work it on 80 Port!
    Service Worker just can work on HTTPS protocol. But you can work on localhost during development.

Service Worker Debugging

You can use Chrome Developer Tools for debugging to Service Worker. Service Worker tools are on the Application tab of Developer Tools. You can see service workers in here that works or waits.

Briefly Developer Console; normally, all windows/tabs that opened must be closed to update an existing service worker. But you can check “Update on Reload” box to update Service Worker every time the page is refreshed. You can update with “Update”, delete with “Unregister”, stop with “Stop”. Also, you can use “Push” button to send Push Notification and “Sync” button to trigger background sync event.

Service Worker Lifecycle

Service Worker lifecycle has 3 step; Registration, Installation, and Activation.

Registration

Service worker is a property of the navigator object of the window. You can use “register” function of serviceWorker to start the registration process. (Note: This function returns “Promise”)

Where should we use registration function?
You can start registration process every page load if you need. Because this process doesn’t start from the beginning every time. If service worker is the new or updated, the installation process will start.

Service Worker Registration Example

register” function must have one parameter that file path that called “sw.js” in this example. It can take the second parameter as an object that has some configurations. “Scope” is the one of these. Scope setting is the “sw.js” file path by default.

Installation (Install Event)

This is the “sw.js” installation process that only triggered if sw.js doesn’t exist or updated.

Install event example

This event is an ideal location for caching static content.

Activation (Activate Event)

This is the event that triggered when the “install” event is completed. If the current page is the out of scope, this isn’t triggered.

Activate event example

This event is the ideal location for removing cached static content if it has a newer version.

Another important point, If you refresh current page when sw.js is updated, you can’t access new one. You must close all existing window/tab and start again for updating. If you want to manage this process from code behind, you can use “self.skipWaiting()“ function in sw.js file, the “install“ event is the ideal location for that.

Fetch Event

You can track and manage page network traffic with this event. You can check existing cache, manage “cache first” and “network first” requests and return a response that you want.

Of course, you can use many different methods but you can find in the following example has “cache first” and “network first” approach. In this example, if the request’s and current location’s origin are the same (Static content is requested.), this called “cacheFirst” but if request targeted external URL, this called “networkFirst”.

CacheFirst: In this function, if the received request has cached before, the cached response is returned to the page. But if not, new response requested from the network.

NetworkFirst: In this function, firstly we can try getting an updated response from the network, if this process completed successfully, the new response will be cached and returned. But if this process failed, we check that request have cached before or not. If cache exists, it is returned to the page, but if not, this is up to you. You can return dummy content or information message to the page.

Background Sync (Sync Event)

Background Sync is a Web API that provides to delay a process until Internet connection has stable. We can adapt this definition to the real world; there is an e-mail client application that works on the browser and we want to send an email with this tool. Internet connection is broken while we are writing e-mail content and we didn’t realize it. When completed the writing, we click send button.
Here is a job for the Background Sync.

In the following view shows classical process sending email to us. If the Internet Connection is broken, we can’t send any content to Mail Server.

In here, you can create any scenario for yourself. A sample is in the following for this case.

  1. When we click “send” button, e-mail content will be saved to IndexedDB.
  2. Background Sync registration.
  3. If the Internet connection is available, all e-mail content will be read and sent to Mail Server.
    If the Internet connection is unavailable, service worker waits until the connection is available even though the window is closed. When it is available, e-mail content will be sent to Mail Server.

You can see working process within the following code block.

Event Listener for Background Sync registration
Evet Listener for sw.js

Push Event

This is the event that handles push notifications that received from the server. You can apply any method with received data.

We can check in the following example.

Notification.requestPermission();” is the necessary line for show notification to user. If you don’t want to show any notification, you don’t need this line.

In the following code block is in sw.js file. You can handle push notifications with this event. In this example, I kept simple. We send an object that has “method” and “message” properties. If method value is “pushMessage”, we open information notification with “message” property.

You can use Application Tab from Chrome Developer Tools for testing push notification.

Conclusion

You can do notification management, background sync and cache with the Service Worker API and some third-party APIs like Cache API. All major browsers don’t support yet, therefore, you can’t access all users with these features. But latest Firefox, Chrome, and Opera versions support. It is known Microsoft Edge and Safari will support in their next versions. Also, you can develop Progressive Web App that is fast and user-friendly with Service Worker API like mobile applications.

References

--

--

Ceyhun Keklik
Commencis

Computer Engineer & Full Stack Developer / Engineering Lead @Dataroid