Skip to content

Commit 0edb081

Browse files
committed
Added catches to fetch calls to catch timeout and connection errors
1 parent 7a15dd9 commit 0edb081

File tree

1 file changed

+33
-22
lines changed

1 file changed

+33
-22
lines changed

packages/react-scripts/template/src/registerServiceWorker.js

+33-22
Original file line numberDiff line numberDiff line change
@@ -17,27 +17,38 @@ export default function register() {
1717
// No service worker yet
1818
registerServiceWorker(swUrl);
1919
} else {
20-
fetch(swUrl).then(res => {
21-
// Check to see if the SW URL is valid
22-
if (res.ok) {
23-
// Matches. All good. Continue with registering SW
24-
registerServiceWorker(swUrl);
25-
} else {
26-
// SW URL was invalid.
27-
fetch(
28-
`${window.location.protocol}//${window.location.host}`
29-
).then(res2 => {
30-
// Just check if online
31-
if (res2.ok) {
32-
// Unregister and refresh page
33-
unregister();
34-
window.location.reload(true);
35-
} else {
36-
console.log('Offline. Using cached copy');
37-
}
38-
});
39-
}
40-
});
20+
fetch(swUrl)
21+
.then(res => {
22+
// Check to see if the SW URL is valid
23+
if (res.ok) {
24+
// Matches. All good. Continue with registering SW
25+
registerServiceWorker(swUrl);
26+
} else {
27+
// SW URL was invalid.
28+
fetch(`${window.location.protocol}//${window.location.host}`)
29+
.then(res2 => {
30+
// Just check if online
31+
if (res2.ok) {
32+
// Unregister and refresh page
33+
unregister();
34+
window.location.reload(true);
35+
} else {
36+
console.log('Offline. Using cached copy');
37+
}
38+
})
39+
.catch(err => {
40+
// Host down. Do nothing.
41+
console.log(
42+
`Caught - fetch ${window.location.protocol}//${window.location.host}`,
43+
err
44+
);
45+
});
46+
}
47+
})
48+
.catch(err => {
49+
// Couldn't access service worker url becaose of timeout/fetch error. Do nothing.
50+
console.log(`Caught - fetch ${swUrl}`, err);
51+
});
4152
}
4253
});
4354
}
@@ -47,7 +58,7 @@ function registerServiceWorker(url) {
4758
navigator.serviceWorker
4859
.register(url)
4960
.then(registration => {
50-
console.log('reg.scope', registration.scope);
61+
console.log('register', registration);
5162
registration.onupdatefound = () => {
5263
const installingWorker = registration.installing;
5364
installingWorker.onstatechange = () => {

0 commit comments

Comments
 (0)