我正在使用 nuxt/pwa 模块创建一个 pwa。我设法在工作箱的安装事件中检测到服务工作人员的更改:
plugins/pwa-update.js
export default async (context) => {
const workbox = await window.$workbox
if (!workbox) {
alert("Workbox couldn't be loaded.")
return
}
workbox.addEventListener('installed', (event) => {
if (!event.isUpdate) {
alert('The PWA is on the latest version.')
return
}
console.log(workbox)
alert('There is an update for the PWA, reloading...')
window.location.reload()
})
}
并使用以下命令清除旧的缓存版本:
#static/custom-sw.js
self.addEventListener('activate', (event) => {
const LATEST_VERSION = 'v0.998'
if (caches) {
caches.keys().then((arr) => {
arr.forEach((key) => {
if (key.indexOf('app-precache') < -1) {
caches
.delete(key)
.then(() =>
console.log(
`%c Cleared ${key}`,
'background: #333; color: #ff0000'
)
)
} else {
caches.open(key).then((cache) => {
cache.match('version').then((res) => {
if (!res) {
cache.put(
'version',
new Response(LATEST_VERSION, {
status: 200,
statusText: LATEST_VERSION,
})
)
} else if (res.statusText !== LATEST_VERSION) {
caches
.delete(key)
.then(() =>
console.log(
`%c Cleared Cache ${res.statusText}`,
'background: #333; color: #ff0000'
)
)
} else {
console.log(
`%c Great you have the latest version ${LATEST_VERSION}`,
'background: #333; color: #00ff00'
)
}
})
})
}
})
})
}
})
这是我的nuxt.config.js
export default {
// Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
ssr: false,
...,
plugins: [
...,
{ src: '~/plugins/pwa-update.js', ssr: false },
],
pwa: {
meta: {
title: 'App',
description: 'App',
author: '...',
},
icon: {
source: 'icon2.png',
fileName: 'icon2.png',
iconSrc: 'icon2.png',
},
manifest: {
name: 'App',
short_name: 'App',
lang: 'it',
theme_color: '#0ca86c',
background_color: '#0ca86c',
useWebmanifestExtension: false,
display: 'standalone',
start_url: '/',
},
workbox: {
enabled: true,
cacheNames: {
prefix: 'app',
},
importScripts: [
'custom-sw.js',
],
},
},
}
但是,我真的不明白更新检测是如何工作的。例如,如果我在 custom-sw.js 文件中使用更新版本部署新的服务器端版本,我仍然需要手动重新加载页面来检测更改并显示新版本警报。我没想到用户必须手动重新加载页面。是否可以在不重新加载页面的情况下触发 pwa-update 事件监听器?
例如,通过推送通知?