Skip to content
This repository has been archived by the owner on Dec 2, 2024. It is now read-only.

Commit

Permalink
fix: Add provide('swHasUpgrade', hasUpgrade) and prevent automatic up…
Browse files Browse the repository at this point in the history
…grade and reload of service worker
  • Loading branch information
richtera committed Oct 30, 2024
1 parent ba3f175 commit 68e1c6d
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 9 deletions.
27 changes: 22 additions & 5 deletions app.vue
Original file line number Diff line number Diff line change
Expand Up @@ -216,12 +216,29 @@ useHead({
return bodyClass.join(' ')
}),
},
script: [
{
innerHTML: `if('serviceWorker' in navigator){window.addEventListener('load', () => {navigator.serviceWorker.register('/sw.js', { scope: '/' })})}`,
},
],
})
const hasUpgrade = ref<boolean>(false)
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(registration => {
// Listen for updates
registration.addEventListener('updatefound', () => {
const newWorker = registration.installing
if (newWorker) {
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'activated') {
// Notify the user that an update is available
console.log('A new version is available. Please refresh.')
hasUpgrade.value = true
// Optionally, prompt the user for a refresh, or defer it to a better time.
}
})
}
})
})
}
// Make the service worker update available to the rest of the app
// any view can use
provide('swHasUpgrade', hasUpgrade)
</script>

<template>
Expand Down
13 changes: 9 additions & 4 deletions service-worker/sw.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { keccak256 } from 'js-sha3'
import { clientsClaim } from 'workbox-core'
/// <reference lib="WebWorker" />
/// <reference types="vite/client" />
import { cleanupOutdatedCaches, precacheAndRoute } from 'workbox-precaching'
Expand Down Expand Up @@ -57,6 +56,12 @@ registerRoute(
)
// registerRoute(new NavigationRoute(createHandlerBoundToURL('/'), { allowlist }))

// @ts-ignore
self.skipWaiting()
clientsClaim()
self.addEventListener('install', () => {
self.skipWaiting() // Skip waiting to activate the new SW immediately
})

self.addEventListener('activate', event => {
event.waitUntil(
self.clients.claim() // Ensure the SW controls the clients
)
})
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// https://nuxt.com/docs/guide/concepts/typescript
"extends": "./.nuxt/tsconfig.json",
"compilerOptions": {
"lib": ["webworker", "dom", "esnext"],
"paths": {
"@/*": [
"./*"
Expand Down

0 comments on commit 68e1c6d

Please sign in to comment.