Closed souldanger closed 5 years ago
Thanks for your PR.
you are welcome! might come up with more...
do you have any recommendations / example as of how to show a toast notifictaion on update? Thanks!
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
}
});
added #{@site.baseurl.to_s}