1// This optional code is used to register a service worker.
  2// register() is not called by default.
  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 subsequent visits to a page, after all the
  7// existing tabs open on the page have been closed, since previously cached
  8// resources are updated in the background.
  9
 10// To learn more about the benefits of this model and instructions on how to
 11// opt-in, read https://bit.ly/CRA-PWA
 12
 13const isLocalhost = Boolean(
 14    window.location.hostname === 'localhost' ||
 15        // [::1] is the IPv6 localhost address.
 16        window.location.hostname === '[::1]' ||
 17        // 127.0.0.0/8 are considered localhost for IPv4.
 18        window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
 19);
 20
 21type Config = {
 22    onSuccess?: (registration: ServiceWorkerRegistration) => void;
 23    onUpdate?: (registration: ServiceWorkerRegistration) => void;
 24};
 25
 26export function register(config?: Config) {
 27    if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
 28        // The URL constructor is available in all browsers that support SW.
 29        const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
 30        if (publicUrl.origin !== window.location.origin) {
 31            // Our service worker won't work if PUBLIC_URL is on a different origin
 32            // from what our page is served on. This might happen if a CDN is used to
 33            // serve assets; see https://github.com/facebook/create-react-app/issues/2374
 34            return;
 35        }
 36
 37        window.addEventListener('load', () => {
 38            const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
 39
 40            if (isLocalhost) {
 41                // This is running on localhost. Let's check if a service worker still exists or not.
 42                checkValidServiceWorker(swUrl, config);
 43
 44                // Add some additional logging to localhost, pointing developers to the
 45                // service worker/PWA documentation.
 46                navigator.serviceWorker.ready.then(() => {
 47                    console.log(
 48                        'This web app is being served cache-first by a service ' +
 49                            'worker. To learn more, visit https://bit.ly/CRA-PWA'
 50                    );
 51                });
 52            } else {
 53                // Is not localhost. Just register service worker
 54                registerValidSW(swUrl, config);
 55            }
 56        });
 57    }
 58}
 59
 60function registerValidSW(swUrl: string, config?: Config) {
 61    navigator.serviceWorker
 62        .register(swUrl)
 63        .then((registration) => {
 64            registration.onupdatefound = () => {
 65                const installingWorker = registration.installing;
 66                if (installingWorker === null) {
 67                    return;
 68                }
 69                installingWorker.onstatechange = () => {
 70                    if (installingWorker.state === 'installed') {
 71                        if (navigator.serviceWorker.controller) {
 72                            // At this point, the updated precached content has been fetched,
 73                            // but the previous service worker will still serve the older
 74                            // content until all client tabs are closed.
 75                            console.log(
 76                                'New content is available and will be used when all ' +
 77                                    'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
 78                            );
 79
 80                            // Execute callback
 81                            if (config && config.onUpdate) {
 82                                config.onUpdate(registration);
 83                            }
 84                        } else {
 85                            // At this point, everything has been precached.
 86                            // It's the perfect time to display a
 87                            // "Content is cached for offline use." message.
 88                            console.log('Content is cached for offline use.');
 89
 90                            // Execute callback
 91                            if (config && config.onSuccess) {
 92                                config.onSuccess(registration);
 93                            }
 94                        }
 95                    }
 96                };
 97            };
 98        })
 99        .catch((error) => {
100            console.error('Error during service worker registration:', error);
101        });
102}
103
104function checkValidServiceWorker(swUrl: string, config?: Config) {
105    // Check if the service worker can be found. If it can't reload the page.
106    fetch(swUrl, {
107        headers: { 'Service-Worker': 'script' },
108    })
109        .then((response) => {
110            // Ensure service worker exists, and that we really are getting a JS file.
111            const contentType = response.headers.get('content-type');
112            if (response.status === 404 || (contentType !== null && contentType.indexOf('javascript') === -1)) {
113                // No service worker found. Probably a different app. Reload the page.
114                navigator.serviceWorker.ready.then((registration) => {
115                    registration.unregister().then(() => {
116                        window.location.reload();
117                    });
118                });
119            } else {
120                // Service worker found. Proceed as normal.
121                registerValidSW(swUrl, config);
122            }
123        })
124        .catch(() => {
125            console.log('No internet connection found. App is running in offline mode.');
126        });
127}
128
129export function unregister() {
130    if ('serviceWorker' in navigator) {
131        navigator.serviceWorker.ready
132            .then((registration) => {
133                registration.unregister();
134            })
135            .catch((error) => {
136                console.error(error.message);
137            });
138    }
139}