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