github.com/replicatedhq/ship@v0.55.0/web/app/src/registerServiceWorker.ts (about)

     1  // tslint:disable:no-console
     2  // In production, we register a service worker to serve assets from local cache.
     3  
     4  // This lets the app load faster on subsequent visits in production, and gives
     5  // it offline capabilities. However, it also means that developers (and users)
     6  // will only see deployed updates on the 'N+1' visit to a page, since previously
     7  // cached resources are updated in the background.
     8  
     9  // To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
    10  // This link also includes instructions on opting out of this behavior.
    11  // tslint:disable:no-floating-promises
    12  
    13  const isLocalhost = Boolean(
    14    window.location.hostname === "localhost" ||
    15      // [::1] is the IPv6 localhost address.
    16      window.location.hostname === "[::1]" ||
    17      // 127.0.0.1/8 is considered localhost for IPv4.
    18      window.location.hostname.match(
    19        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    20      )
    21  );
    22  
    23  // tslint:disable-next-line:no-default-export
    24  export default function register() {
    25    if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
    26      // The URL constructor is available in all browsers that support SW.
    27      const publicUrl = new URL(
    28        process.env.PUBLIC_URL!,
    29        window.location.toString()
    30      );
    31      if (publicUrl.origin !== window.location.origin) {
    32        // Our service worker won't work if PUBLIC_URL is on a different origin
    33        // from what our page is served on. This might happen if a CDN is used to
    34        // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
    35        return;
    36      }
    37  
    38      window.addEventListener("load", () => {
    39        const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
    40  
    41        if (isLocalhost) {
    42          // This is running on localhost. Lets check if a service worker still exists or not.
    43          checkValidServiceWorker(swUrl);
    44  
    45          // Add some additional logging to localhost, pointing developers to the
    46          // service worker/PWA documentation.
    47          navigator.serviceWorker.ready.then(() => {
    48            console.log(
    49              "This web app is being served cache-first by a service " +
    50                "worker. To learn more, visit https://goo.gl/SC7cgQ"
    51            );
    52          });
    53        } else {
    54          // Is not local host. Just register service worker
    55          registerValidSW(swUrl);
    56        }
    57      });
    58    }
    59  }
    60  
    61  function registerValidSW(swUrl: string) {
    62    navigator.serviceWorker
    63      .register(swUrl)
    64      .then(registration => {
    65        registration.onupdatefound = () => {
    66          const installingWorker = registration.installing;
    67          if (installingWorker) {
    68            installingWorker.onstatechange = () => {
    69              if (installingWorker.state === "installed") {
    70                if (navigator.serviceWorker.controller) {
    71                  // At this point, the old content will have been purged and
    72                  // the fresh content will have been added to the cache.
    73                  // It's the perfect time to display a 'New content is
    74                  // available; please refresh.' message in your web app.
    75                  console.log("New content is available; please refresh.");
    76                } else {
    77                  // At this point, everything has been precached.
    78                  // It's the perfect time to display a
    79                  // 'Content is cached for offline use.' message.
    80                  console.log("Content is cached for offline use.");
    81                }
    82              }
    83            };
    84          }
    85        };
    86      })
    87      .catch(error => {
    88        console.error("Error during service worker registration:", error);
    89      });
    90  }
    91  
    92  function checkValidServiceWorker(swUrl: string) {
    93    // Check if the service worker can be found. If it can't reload the page.
    94    fetch(swUrl)
    95      .then(response => {
    96        // Ensure service worker exists, and that we really are getting a JS file.
    97        if (
    98          response.status === 404 ||
    99          response.headers.get("content-type")!.indexOf("javascript") === -1
   100        ) {
   101          // No service worker found. Probably a different app. Reload the page.
   102          navigator.serviceWorker.ready.then(registration => {
   103            registration.unregister().then(() => {
   104              window.location.reload();
   105            });
   106          });
   107        } else {
   108          // Service worker found. Proceed as normal.
   109          registerValidSW(swUrl);
   110        }
   111      })
   112      .catch(() => {
   113        console.log(
   114          "No internet connection found. App is running in offline mode."
   115        );
   116      });
   117  }
   118  
   119  export function unregister() {
   120    if ("serviceWorker" in navigator) {
   121      navigator.serviceWorker.ready.then(registration => {
   122        registration.unregister();
   123      });
   124    }
   125  }