serviceWorker.js 4.97 KB
Newer Older
d.arizona's avatar
d.arizona committed
1 2 3 4 5 6 7 8 9 10 11 12 13
// This optional code is used to register a service worker.
// register() is not called by default.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.

// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA

const isLocalhost = Boolean(
d.arizona's avatar
d.arizona committed
14
  window.location.hostname === 'localhost' ||
d.arizona's avatar
d.arizona committed
15
    // [::1] is the IPv6 localhost address.
d.arizona's avatar
d.arizona committed
16
    window.location.hostname === '[::1]' ||
d.arizona's avatar
d.arizona committed
17 18 19 20 21 22
    // 127.0.0.0/8 are considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

d.arizona's avatar
d.arizona committed
23 24
export function register(config) {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
d.arizona's avatar
d.arizona committed
25 26 27 28 29 30 31 32 33
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebook/create-react-app/issues/2374
      return;
    }

d.arizona's avatar
d.arizona committed
34
    window.addEventListener('load', () => {
d.arizona's avatar
d.arizona committed
35 36 37 38 39 40 41 42 43 44
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Let's check if a service worker still exists or not.
        checkValidServiceWorker(swUrl, config);

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
d.arizona's avatar
d.arizona committed
45 46
            'This web app is being served cache-first by a service ' +
              'worker. To learn more, visit https://bit.ly/CRA-PWA'
d.arizona's avatar
d.arizona committed
47 48 49 50 51 52 53 54 55 56
          );
        });
      } else {
        // Is not localhost. Just register service worker
        registerValidSW(swUrl, config);
      }
    });
  }
}

d.arizona's avatar
d.arizona committed
57
function registerValidSW(swUrl, config) {
d.arizona's avatar
d.arizona committed
58 59
  navigator.serviceWorker
    .register(swUrl)
d.arizona's avatar
d.arizona committed
60 61
    .then(registration => {
      registration.onupdatefound = () => {
d.arizona's avatar
d.arizona committed
62 63 64 65
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
d.arizona's avatar
d.arizona committed
66 67
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
d.arizona's avatar
d.arizona committed
68 69 70 71 72
            if (navigator.serviceWorker.controller) {
              // At this point, the updated precached content has been fetched,
              // but the previous service worker will still serve the older
              // content until all client tabs are closed.
              console.log(
d.arizona's avatar
d.arizona committed
73 74
                'New content is available and will be used when all ' +
                  'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
d.arizona's avatar
d.arizona committed
75 76 77 78 79 80 81 82 83 84
              );

              // Execute callback
              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
d.arizona's avatar
d.arizona committed
85
              console.log('Content is cached for offline use.');
d.arizona's avatar
d.arizona committed
86 87 88 89 90 91 92 93 94 95

              // Execute callback
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
d.arizona's avatar
d.arizona committed
96 97
    .catch(error => {
      console.error('Error during service worker registration:', error);
d.arizona's avatar
d.arizona committed
98 99 100
    });
}

d.arizona's avatar
d.arizona committed
101
function checkValidServiceWorker(swUrl, config) {
d.arizona's avatar
d.arizona committed
102 103
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl, {
d.arizona's avatar
d.arizona committed
104
    headers: { 'Service-Worker': 'script' },
d.arizona's avatar
d.arizona committed
105
  })
d.arizona's avatar
d.arizona committed
106
    .then(response => {
d.arizona's avatar
d.arizona committed
107
      // Ensure service worker exists, and that we really are getting a JS file.
d.arizona's avatar
d.arizona committed
108
      const contentType = response.headers.get('content-type');
d.arizona's avatar
d.arizona committed
109 110
      if (
        response.status === 404 ||
d.arizona's avatar
d.arizona committed
111
        (contentType != null && contentType.indexOf('javascript') === -1)
d.arizona's avatar
d.arizona committed
112 113
      ) {
        // No service worker found. Probably a different app. Reload the page.
d.arizona's avatar
d.arizona committed
114
        navigator.serviceWorker.ready.then(registration => {
d.arizona's avatar
d.arizona committed
115 116 117 118 119 120 121 122 123 124 125
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl, config);
      }
    })
    .catch(() => {
      console.log(
d.arizona's avatar
d.arizona committed
126
        'No internet connection found. App is running in offline mode.'
d.arizona's avatar
d.arizona committed
127 128 129 130
      );
    });
}

d.arizona's avatar
d.arizona committed
131 132
export function unregister() {
  if ('serviceWorker' in navigator) {
d.arizona's avatar
d.arizona committed
133
    navigator.serviceWorker.ready
d.arizona's avatar
d.arizona committed
134
      .then(registration => {
d.arizona's avatar
d.arizona committed
135 136
        registration.unregister();
      })
d.arizona's avatar
d.arizona committed
137
      .catch(error => {
d.arizona's avatar
d.arizona committed
138 139 140 141
        console.error(error.message);
      });
  }
}