File size: 2,321 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// In production, we register a service worker to serve assets from local cache.

import webPushManager from './helpers/web-push-manager';

// 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 the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.

export type ServiceWorkerResult = {
  newContent?: boolean,
  firstCache?: boolean,
};

const IS_PROD = process.env.NODE_ENV === 'production';

const swUrl = IS_PROD
  ? `${process.env.PUBLIC_URL}/service-worker.js`
  : `${process.env.PUBLIC_URL}/push-sw-v1.js`;

export default function register(): Promise<ServiceWorkerResult> {
  if ('serviceWorker' in navigator) {
    return new Promise(res => {
      window.addEventListener('load', () => {
        navigator.serviceWorker
          .register(swUrl)
          .then(registration => {
            if ('PushManager' in window) {
              webPushManager.set(registration.pushManager);
            }
            registration.onupdatefound = () => {
              const installingWorker = registration.installing;
              installingWorker.onstatechange = () => {
                if (installingWorker.state === 'installed') {
                  if (navigator.serviceWorker.controller) {
                    // At this point, the old content will have been purged and
                    // the fresh content will have been added to the cache.
                    res({ newContent: true });
                  } else {
                    // At this point, everything has been precached.
                    res({ firstCache: true });
                  }
                }
              };
            };
          })
          .catch(error => {
            console.error('Error during service worker registration:', error);
          });
      });
    });
  } else {
    return Promise.resolve({});
  }
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}