lavas-project / jekyll-pwa

Jekyll plugin for PWA
MIT License
107 stars 19 forks source link

added baseurl to navigator.serviceWorker.register #15

Closed souldanger closed 5 years ago

souldanger commented 5 years ago

added #{@site.baseurl.to_s}

PengXing commented 5 years ago

Thanks for your PR.

souldanger commented 5 years ago

you are welcome! might come up with more...

souldanger commented 5 years ago

do you have any recommendations / example as of how to show a toast notifictaion on update? Thanks!

PengXing commented 5 years ago

Actually, we already have one Webpack plugin sw-register-webpack-plugin handled this situation, but only have Chinese version.

It might need several steps.

1. Register Service Worker and listen messages from Service Worker

navigator.serviceWorker && navigator.serviceWorker.register('/service-worker.js').then(() => {
  navigator.serviceWorker.addEventListener('message', e => {
    // Show a toast notification
  });
});

2. Service Worker know if it's updating

Determine if the specified Cache exists, or determine if the specified Cache has some stored keys, once the Service Worker triggered the install event.

const CACHE_NAME = 'CACHE_NAME';
let freshmeat = false;

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHE_NAME).then(function(cache) {
      cache.keys().then(keys => {
        if (!keys || keys.length === 0) {
          freshmeat = true;
        }
        // do other things
      })
    })
  )
});

3. Service Worker posts a message to every clients

Post a message to every hosted clients when Service Worker is coming to activate phase.

See this code example

self.clients.matchAll()
  .then(function (clients) {
    if (clients && clients.length) {
      clients.forEach(function (client) {
        client.postMessage('sw.update');
      })
    }
  })

4. Show a toast notification

The message from Service Worker captured by the listener registered in the step 1. If the message equals to sw.update, then show a toast notification.

See this code example

navigator.serviceWorker.addEventListener('message', e => {
  if (e.data === 'sw.update') {
    // Show the toast notification
  }
});