Skip to content

Instantly share code, notes, and snippets.

@luke-denton-aligent
Last active September 17, 2022 23:28
Show Gist options
  • Save luke-denton-aligent/6c832e48d6658f817611b12d203719f4 to your computer and use it in GitHub Desktop.
Save luke-denton-aligent/6c832e48d6658f817611b12d203719f4 to your computer and use it in GitHub Desktop.
This snippet shows how to trigger an update for a service worker, so it is not waiting for the old service worker to stop controlling a page
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
//Using the example from https://gist.github.com/luke-denton/e52cff8e13fc4efa0f9d83d7729304d1
IndexController.prototype._registerServiceWorker = function() {
// ... (see https://gist.github.com/luke-denton/e52cff8e13fc4efa0f9d83d7729304d1 for the rest of this function body
//Listen for the controllerchange event, which will mean a new service worker has taken control
navigator.serviceWorker.addEventListener('controllerchange', function() {
window.location.reload();
});
}
//This is just the _updateReady function, as the only change needed in here is when the user clicks the Refresh button
IndexController.prototype._updateReady = function() {
var toast = this._toastsView.show("New version available", {
buttons: ['refresh', 'dismiss']
});
//Again, this is just how this certain plugin works, the main take away is the worker.postMessage() call
toast.answer.then(function(answer) {
if (answer != 'refresh') return;
//User clicked the refresh button, so send a message to the service worker that it should activate itself without waiting
worker.postMessage({action: 'skipWaiting'});
});
}
// In sw.js (The service worker)
//Listen for the message event
self.addEventListener('message', function(event) {
//Check if the received message is indicating to skip waiting
if (event.data.action === 'skipWaiting') {
//Tell service worker not to wait for old service worker to be idle before activing
self.skipWaiting();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment