Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mhadaily/c8b2dea5d1c597b27496e6d7319dbee9 to your computer and use it in GitHub Desktop.
Save mhadaily/c8b2dea5d1c597b27496e6d7319dbee9 to your computer and use it in GitHub Desktop.
Use it in your index.html file in Flutter Web.
function invokeServiceWorkerUpdateFlow() {
  // you have a better UI here, reloading is not a great user experince here.
  const confirmed = confirm('New version of the app is available. Refresh now');
  if (confirmed) {
    window.location.reload();
  }
}
async function handleServiceWorker() {
  if ('serviceWorker' in navigator) {
    // get the ServiceWorkerRegistration instance
    const registration = await navigator.serviceWorker.getRegistration();
    // (it is also returned from navigator.serviceWorker.register() function)

    if (registration) {
      // detect Service Worker update available and wait for it to become installed
      registration.addEventListener('updatefound', () => {
        if (registration.installing) {
          // wait until the new Service worker is actually installed (ready to take over)
          registration.installing.addEventListener('statechange', () => {
            if (registration.waiting) {
              // if there's an existing controller (previous Service Worker), show the prompt
              if (navigator.serviceWorker.controller) {
                invokeServiceWorkerUpdateFlow(registration);
              } else {
                // otherwise it's the first install, nothing to do
                console.log('Service Worker initialized for the first time');
              }
            }
          });
        }
      });

      let refreshing = false;

      // detect controller change and refresh the page
      navigator.serviceWorker.addEventListener('controllerchange', () => {
        if (!refreshing) {
          window.location.reload();
          refreshing = true;
        }
      });
    }
  }
}

handleServiceWorker();
@mhadaily
Copy link
Author

mhadaily commented May 3, 2021

Well, do you have a Dart project or it's a Flutter project? If it's Flutter, you can copy and paste this at the bottom of the index.html file.
or leverage Dart:js / HTML to convert this to a dart code.

Luckily, I have news for you. I am working on a project that enables you to write your service worker-related stuff in pure Dart. stay tuned. I'll announce it sometime before July 2021.

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