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

Commit

Permalink
feat(workbox): auto unregister when not enabled (#92)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinmarrec authored Feb 4, 2023
1 parent 965416f commit 5b45153
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 13 deletions.
31 changes: 18 additions & 13 deletions src/parts/workbox/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,25 @@ import type { WorkboxOptions } from './types'

const consola = _consola.create({ level: process.env.NUXT_PWA_SILENT === '1' ? -Infinity : undefined })

function addNitroPlugin (nuxt: ReturnType<typeof useNuxt>, plugin: string) {
nuxt.hook('nitro:config', (config) => {
config.externals = config.externals || {}
config.externals.inline = config.externals.inline || []
config.externals.inline.push(plugin)
config.plugins = config.plugins || []
config.plugins.push(plugin)
})
}

export default async (pwa: PWAContext) => {
if (!pwa.workbox || !pwa.workbox.enabled)
return
const nuxt = useNuxt()

if (!pwa.workbox || !pwa.workbox.enabled) {
// Unregister Service Worker
return addNitroPlugin(nuxt, pwa._resolver.resolve('./runtime/nitro/unregister-plugin'))
}

const options = pwa.workbox
const nuxt = useNuxt()

// Warning when in development mode
if (nuxt.options.dev)
Expand Down Expand Up @@ -41,14 +54,6 @@ export default async (pwa: PWAContext) => {
})

// Register Service Worker
if (options.autoRegister) {
nuxt.hook('nitro:config', (config) => {
const plugin = pwa._resolver.resolve('./runtime/nitro-plugin')
config.externals = config.externals || {}
config.externals.inline = config.externals.inline || []
config.externals.inline.push(plugin)
config.plugins = config.plugins || []
config.plugins.push(plugin)
})
}
if (options.autoRegister)
addNitroPlugin(nuxt, pwa._resolver.resolve('./runtime/nitro/register-plugin'))
}
File renamed without changes.
31 changes: 31 additions & 0 deletions src/runtime/nitro/unregister-plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { NitroAppPlugin } from 'nitropack'

export default <NitroAppPlugin> function (nitro) {
nitro.hooks.hook('render:html', (htmlContext) => {
htmlContext.head.push(
[
'<script>',
'if (\'serviceWorker\' in navigator) {',
' navigator.serviceWorker.getRegistrations().then((registrations) => {',
' for (const registration of registrations) {',
' console.info(\'[PWA] Unregistering Service Worker:\', registration)',
' registration.unregister()',
' }',
' })',
'}',
'if (\'caches\' in window) {',
' caches.keys()',
' .then((keys) => {',
' if (keys.length) {',
' console.info(\'[PWA] Cleaning cache for:\', keys.join(\', \'))',
' for (const key of keys) {',
' caches.delete(key)',
' }',
' }',
' })',
'}',
'</script>',
].join('\n'),
)
})
}

0 comments on commit 5b45153

Please sign in to comment.