每当使用Notification API更新预缓存的内容时,我都试图向用户显示通知。在config.onUpdate(registration)
中,我通过了registration
。每当注册新服务工作者时,都会调用registration.onupdatefound
,其中使用navigator.serviceWorker.controller
检查serviceWorker是否已“激活”
如果它被激活,那么我正在显示通知。
function registerValidSW(swUrl: string, config?: Config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
Notification.requestPermission();
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
"New content is available and will be used when all " +
"tabs for this page are closed.PWA."
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log("Content is cached for offline use.");
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error("Error during service worker registration:", error);
});
}
let config ={
onUpdate:(registration: ServiceWorkerRegistration)=>{
if (Notification.permission == 'granted') {
registration.showNotification('New content is available; please refresh.');
}
}
};
预期输出:-只要有更新的预缓存内容就应调用config.onUpdate()
。
实际输出:-刷新页面时,我会收到通知。