Introduction to Service Worker

  1. Check if service worker is supported
  2. Register a service worker
  3. Check if a service worker exists in a given URL
  • How to use navigator.serviceWorker.ready property?
    1. I want the service worker to control higher pages
    2. Listen for install event in service worker
    3. Listen for activate event in service worker

    Check if service worker is supported

    main.js

    1
    2
    3
    4
    5
    if ('serviceWorker' in navigator) {
    // supported!
    } else {
    // Service workers are not supported.
    }

    Register a service worker

    main.js

    1
    2
    3
    4
    5
    6
    7
    navigator.serviceWorker.register('sw.js')
    .then(registration => {
    console.log(`Registration successful, scope is ${registration.scope}`);
    })
    .catch(error => {
    console.log(`Service worker registration failed, error: ${error}`);
    })

    Check if a service worker exists in a given URL

    If you want to do this in code, you can only do it within the same origin as the worker(s) you want to check for. Within the same origin, you can use getRegistration(url) (which gives you a promise that will resolve to undefined or a ServiceWorkerRegistration object for the URL), or getRegistrations() (which gives you a promise for an array of ServiceWorkerRegistration objects). E.g.:

    main.js

    1
    2
    3
    navigator.serviceWorker.getRegistrations().then(registrations => {
    console.log(registrations);
    });

    How to use navigator.serviceWorker.ready property?

    I want the service worker to control higher pages

    1. Change the scope option when registering the service worker

    main.js

    1
    2
    3
    navigator.serviceWorker.register('/app/service-worker.js', {
    scope: '/app'
    });
    1. Set the Service-Worker-Allowed HTTP header in your server config for the request serving the service worker script.

    nginx config

    1
    2
    3
    4
    location ~* (service-worker\.js)$ {
    # tells browsers the service worker scope
    add_header 'Service-Worker-Allowed' '/app';
    }

    Apache config

    1
    2
    3
    4
    LoadModule rewrite_module modules/mod_rewrite.so
    <Files "service-worker.js">
    Header set Service-Worker-Allowed "/"
    </Files>

    Listen for install event in service worker

    service-worker.js

    1
    2
    3
    4
    // Listen for install event, set callback
    self.addEventListener('install', function(event) {
    // Perform some task
    });

    Listen for activate event in service worker

    service-worker.js

    1
    2
    3
    self.addEventListener('activate', function(event) {
    // Perform some task
    });