Skip to content

Instantly share code, notes, and snippets.

@arash16
Last active September 14, 2022 12:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arash16/324f2b46ff450687257ef42409a47daa to your computer and use it in GitHub Desktop.
Save arash16/324f2b46ff450687257ef42409a47daa to your computer and use it in GitHub Desktop.
// this code is executed in the context of each tab
import {Workbox} from 'workbox-window';
if ('serviceWorker' in navigator) {
const wb = new Workbox('/sw.js');
wb.addEventListener('waiting', () => {
console.log('A new service worker has installed');
wb.addEventListener('controlling', () => {
// (3) as soon as the new service worker has taken control,
// ask service worker to tell all open tabs to reload.
wb.messageSW({type: 'RELOAD'});
});
// (1) Send a message telling the service worker to skip waiting.
// This will trigger the `controlling` event handler above.
// Note: for this to work, you have to add a message
// listener in your service worker.
wb.messageSW({type: 'SKIP_WAITING'});
});
navigator.serviceWorker.addEventListener('message', event => {
// (5) service workers says we should reload
if (event.data && event.data.type === 'RELOAD') {
window.location.reload();
}
});
wb.register();
}
// this is the code of actual service worker. for all open tabs
// there's at most one instance of this service worker running
// ...
addEventListener('message', (event) => {
if (event.data) {
switch (event.data.type) {
case 'SKIP_WAITING':
// (2) new service worker is installed and is asking to take control
// (he is in hurry and can't wait)
skipWaiting();
break;
case 'RELOAD':
// (4) someone just told us that new service worker is in control
// lets tell all open tabs to reload
clients.matchAll().then(clients => {
clients.forEach(client => client.postMessage({type: 'RELOAD'}));
});
break;
}
}
});
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment