Skip to content

Commit d95eda9

Browse files
authored
Add files via upload
1 parent 45ab7d8 commit d95eda9

File tree

2 files changed

+209
-0
lines changed

2 files changed

+209
-0
lines changed

src/service-worker.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/* eslint-disable no-restricted-globals */
2+
3+
// This service worker can be customized!
4+
// See https://developers.google.com/web/tools/workbox/modules
5+
// for the list of available Workbox modules, or add any other
6+
// code you'd like.
7+
// You can also remove this file if you'd prefer not to use a
8+
// service worker, and the Workbox build step will be skipped.
9+
10+
import { clientsClaim } from 'workbox-core';
11+
import { ExpirationPlugin } from 'workbox-expiration';
12+
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
13+
import { registerRoute } from 'workbox-routing';
14+
import { StaleWhileRevalidate } from 'workbox-strategies';
15+
16+
clientsClaim();
17+
18+
// Precache all of the assets generated by your build process.
19+
// Their URLs are injected into the manifest variable below.
20+
// This variable must be present somewhere in your service worker file,
21+
// even if you decide not to use precaching. See https://cra.link/PWA
22+
precacheAndRoute(self.__WB_MANIFEST);
23+
24+
// Set up App Shell-style routing, so that all navigation requests
25+
// are fulfilled with your index.html shell. Learn more at
26+
// https://developers.google.com/web/fundamentals/architecture/app-shell
27+
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
28+
registerRoute(
29+
// Return false to exempt requests from being fulfilled by index.html.
30+
({ request, url }) => {
31+
// If this isn't a navigation, skip.
32+
if (request.mode !== 'navigate') {
33+
return false;
34+
} // If this is a URL that starts with /_, skip.
35+
36+
if (url.pathname.startsWith('/_')) {
37+
return false;
38+
} // If this looks like a URL for a resource, because it contains // a file extension, skip.
39+
40+
if (url.pathname.match(fileExtensionRegexp)) {
41+
return false;
42+
} // Return true to signal that we want to use the handler.
43+
44+
return true;
45+
},
46+
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
47+
);
48+
49+
// An example runtime caching route for requests that aren't handled by the
50+
// precache, in this case same-origin .png requests like those from in public/
51+
registerRoute(
52+
// Add in any other file extensions or routing criteria as needed.
53+
({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'), // Customize this strategy as needed, e.g., by changing to CacheFirst.
54+
new StaleWhileRevalidate({
55+
cacheName: 'images',
56+
plugins: [
57+
// Ensure that once this runtime cache reaches a maximum size the
58+
// least-recently used images are removed.
59+
new ExpirationPlugin({ maxEntries: 50 }),
60+
],
61+
})
62+
);
63+
64+
// This allows the web app to trigger skipWaiting via
65+
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
66+
self.addEventListener('message', (event) => {
67+
if (event.data && event.data.type === 'SKIP_WAITING') {
68+
self.skipWaiting();
69+
}
70+
});
71+
72+
// Any other custom service worker logic can go here.

src/serviceWorkerRegistration.js

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

0 commit comments

Comments
 (0)