Skip to content

Commit 0d92d39

Browse files
Fix SW issues
1 parent 452afee commit 0d92d39

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

assets/js/global.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
const registerServiceWorker = async () => {
2+
if ("serviceWorker" in navigator) {
3+
try {
4+
const registration = await navigator.serviceWorker.register("/service_worker.js", {
5+
scope: "/",
6+
});
7+
if (registration.installing) {
8+
console.log("Service worker installing");
9+
} else if (registration.waiting) {
10+
console.log("Service worker installed");
11+
} else if (registration.active) {
12+
console.log("Service worker active");
13+
}
14+
} catch (error) {
15+
console.error(`Registration failed with ${error}`);
16+
}
17+
}
18+
};
19+
20+
registerServiceWorker();

service_worker.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// sw.js
2+
3+
self.addEventListener('install', () => {
4+
// Skip over the "waiting" lifecycle state, to ensure that our
5+
// new service worker is activated immediately, even if there's
6+
// another tab open controlled by our older service worker code.
7+
self.skipWaiting();
8+
});
9+
10+
self.addEventListener('activate', () => {
11+
// Optional: Get a list of all the current open windows/tabs under
12+
// our service worker's control, and force them to reload.
13+
// This can "unbreak" any open windows/tabs as soon as the new
14+
// service worker activates, rather than users having to manually reload.
15+
self.clients.matchAll({
16+
type: 'window'
17+
}).then(windowClients => {
18+
windowClients.forEach((windowClient) => {
19+
windowClient.navigate(windowClient.url);
20+
});
21+
});
22+
});

0 commit comments

Comments
 (0)