Skip to content

Instantly share code, notes, and snippets.

@abdulhannanali
Created July 2, 2017 11:38
Show Gist options
  • Save abdulhannanali/64213c82c139eb076fe9c0bec2ca77d7 to your computer and use it in GitHub Desktop.
Save abdulhannanali/64213c82c139eb076fe9c0bec2ca77d7 to your computer and use it in GitHub Desktop.
Show a ServiceWorker Installed Popup
// Display a Information about ServiceWorker Installation being Completed.
// An alternative and more battle tested way to do the same thing is found on Google I/O 2016 PWA (IOWA)
// https://github.com/GoogleChrome/ioweb2016/blob/8cfa27261f9d07fe8a5bb7d228bd3f35dfc9a91e/app/scripts/helper/service-worker-registration.js#L34-L46
/// One way to register the Caching complete event for the service workers
/// I am using this in my application and this seems to be working
if ('serviceWorker' in navigator) {
const initialController = navigator.serviceWorker.controller;
navigator.serviceWorker.register('./serviceWorker.js').then(registration => {
if (registration.installing) {
var serviceWorker = registration.installing;
serviceWorker.addEventListener('statechange', function (event) {
if (event.target.state === 'installed' && !initialController) {
showPopup();
}
});
}
});
}
@abdulhannanali
Copy link
Author

@jakearchibald This also seems to be working, above approaches, are perfect for a more fine grained control, but this seems simpler

navigator.serviceWorker.ready.then(registration => {
  if (!navigator.serviceWorker.controller) {
    showPopup();
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment