Skip to content

Commit 7db5bc3

Browse files
authored
Merge pull request #24 from blueedgetechno/andrewstech-patch-1
Fix Service worker
2 parents cd294a6 + d95eda9 commit 7db5bc3

File tree

3 files changed

+94
-20
lines changed

3 files changed

+94
-20
lines changed

src/index.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import './index.css';
44
import App from './App';
55
import store from './store';
66
import { Provider } from 'react-redux';
7-
import * as serviceWorker from './serviceWorker';
7+
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
88

99
ReactDOM.render(
1010
<React.StrictMode>
@@ -18,4 +18,4 @@ ReactDOM.render(
1818
// If you want your app to work offline and load faster, you can change
1919
// unregister() to register() below. Note this comes with some pitfalls.
2020
// Learn more about service workers: https://bit.ly/CRA-PWA
21-
serviceWorker.register();
21+
serviceWorkerRegistration.register();

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/serviceWorker.js renamed to src/serviceWorkerRegistration.js

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,14 @@
88
// resources are updated in the background.
99

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

1313
const isLocalhost = Boolean(
1414
window.location.hostname === 'localhost' ||
1515
// [::1] is the IPv6 localhost address.
1616
window.location.hostname === '[::1]' ||
17-
// 127.0.0.1/8 is 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-
)
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}$/)
2119
);
2220

2321
export function register(config) {
@@ -43,7 +41,7 @@ export function register(config) {
4341
navigator.serviceWorker.ready.then(() => {
4442
console.log(
4543
'This web app is being served cache-first by a service ' +
46-
'worker. To learn more, visit https://bit.ly/CRA-PWA'
44+
'worker. To learn more, visit https://cra.link/PWA'
4745
);
4846
});
4947
} else {
@@ -57,7 +55,7 @@ export function register(config) {
5755
function registerValidSW(swUrl, config) {
5856
navigator.serviceWorker
5957
.register(swUrl)
60-
.then(registration => {
58+
.then((registration) => {
6159
registration.onupdatefound = () => {
6260
const installingWorker = registration.installing;
6361
if (installingWorker == null) {
@@ -71,7 +69,7 @@ function registerValidSW(swUrl, config) {
7169
// content until all client tabs are closed.
7270
console.log(
7371
'New content is available and will be used when all ' +
74-
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
72+
'tabs for this page are closed. See https://cra.link/PWA.'
7573
);
7674

7775
// Execute callback
@@ -93,23 +91,25 @@ function registerValidSW(swUrl, config) {
9391
};
9492
};
9593
})
96-
.catch(error => {
94+
.catch((error) => {
9795
console.error('Error during service worker registration:', error);
9896
});
9997
}
10098

10199
function checkValidServiceWorker(swUrl, config) {
102100
// Check if the service worker can be found. If it can't reload the page.
103-
fetch(swUrl)
104-
.then(response => {
101+
fetch(swUrl, {
102+
headers: { 'Service-Worker': 'script' },
103+
})
104+
.then((response) => {
105105
// Ensure service worker exists, and that we really are getting a JS file.
106106
const contentType = response.headers.get('content-type');
107107
if (
108108
response.status === 404 ||
109109
(contentType != null && contentType.indexOf('javascript') === -1)
110110
) {
111111
// No service worker found. Probably a different app. Reload the page.
112-
navigator.serviceWorker.ready.then(registration => {
112+
navigator.serviceWorker.ready.then((registration) => {
113113
registration.unregister().then(() => {
114114
window.location.reload();
115115
});
@@ -120,16 +120,18 @@ function checkValidServiceWorker(swUrl, config) {
120120
}
121121
})
122122
.catch(() => {
123-
console.log(
124-
'No internet connection found. App is running in offline mode.'
125-
);
123+
console.log('No internet connection found. App is running in offline mode.');
126124
});
127125
}
128126

129127
export function unregister() {
130128
if ('serviceWorker' in navigator) {
131-
navigator.serviceWorker.ready.then(registration => {
132-
registration.unregister();
133-
});
129+
navigator.serviceWorker.ready
130+
.then((registration) => {
131+
registration.unregister();
132+
})
133+
.catch((error) => {
134+
console.error(error.message);
135+
});
134136
}
135137
}

0 commit comments

Comments
 (0)