Service Workers – Introduction

A service worker is a script that runs in the background and does not require the web page to load. It runs on a separate thread and cannot directly access the DOM. It interacts with webpages through the post messages.

For the first time, I used service workers to push notification, and it is effortless to integrate it, in your javascript code.

The service worker is asynchronous and cannot use XHR and localStorage inside it.

Register a Service Worker

The service worker must be registered before the script can run, and notify the user where the script is. So, it can be downloaded, installed, and activated.

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/ServiceWorker.js')
  .then(function(response) {
    
    // Service worker registration done
    console.log('Registration Successful', response);
  }, function(error) {
    // Service worker registration failed
    console.log('Registration Failed', error);
  }

once the service worker is registered, it shows in the devTools.

LifeCycle of a Service Worker

  1. Download
  2. Install
  3. Activate

Firstly, the browser downloads a file that contains the service worker. It is downloaded when the browser loads the webpage. Secondly, the file is installed only if the content is new or updated. At last, the service worker gets activated.

Populating the Cache

We use the service worker’s brand new storage API (cache) - a global object on the service worker that allows us to store assets delivered by responses, and keyed by their requests. This API works in a similar way to the browser’s standard cache, but it is specific to your domain. Moreover, it persists until you tell it not to.

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('v1').then((cache) => {
      return cache.addAll([
        './sw/',
        './sw/index.html'
      ]);
    })
  );
});

Response to Requests

A fetch event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents.

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
  );
});

Push Notification

Sending push notification to the user has two steps. First, we request permission to allow so that browser can send a notification to the user.
Then, a new notification is sent using the notification() constructor.

self.addEventListener("push", function(e) {

    var body,
      notification = {};
    let notification_data = e.data.json();

    if (notification_data) {
      notification = notification_data.notification;
      if (e.data) {
        body = notification.body;
      } else {
        body = "";
      }
      var options = {
        body: body,
        image: notification.image,
        icon: "./logo.png",
        vibrate: [100, 50, 100],
        data: {
          dateOfArrival: Date.now(),
          primaryKey: 1
        }
        actions: [
        {action: 'explore', title: 'Explore this new world',
            icon: 'favicon.ico'
        },
        {action: 'close', title: 'I don\'t want any of this',
            icon: 'images/xmark.png'
        },
        ]
      };
      e.waitUntil(
        self.registration.showNotification(notification.title, options);
      );
    }
  });
});

The notification is triggered via. the push event and displayed when showNotification() method is called by the service worker.

excellence-social-linkdin
excellence-social-facebook
excellence-social-instagram
excellence-social-skype