我使用Service Worker创建了一个简单的PWA应用,可以在需要时从服务器接收推送通知并为用户显示通知。当应用程序在前台运行时,这很好用,当应用程序在后台运行几分钟时,推送通知将按预期接收并显示给用户。但是,如果应用程序在后台运行超过几分钟或关闭应用程序,则PWA将停止接收这些推送通知。
我目前所拥有的内容:
service-worker.js
我目前所拥有的内容:
service-worker.js
self.addEventListener('push', (e) => {
let notificationData
e.waitUntil(
clients.matchAll({ type: 'window' }).then(function(clientList) {
const client = clientList && clientList[0]
if (e.data && client && client.visibilityState !== 'visible') {
const envelope = e.data.json()
// Process the notification
// ...
e.waitUntil(self.registration.showNotification(data.subject, options))
}
})
)
})
index.js
async registerPushNotificationToWorker() {
if ('serviceWorker' in navigator) {
try {
const swRegistration = await navigator.serviceWorker.getRegistration()
let subscription = await swRegistration.pushManager.getSubscription()
let subscriptionJson
if (subscription === null) {
subscriptionJson = await subscribeUser()
} else {
subscriptionJson = subscription.toJSON()
}
// Save subscriptionJson on server
// ...
} catch (e) {
console.log('Service Worker registration failed: ', e)
}
}
}
async subscribeUser() {
if ('serviceWorker' in navigator) {
const swRegistration = await navigator.serviceWorker.ready
try {
const pushSubscription = await swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey
})
return pushSubscription.toJSON()
} catch (e) {
console.log('Error', e)
if (Notification.permission === 'denied') {
console.warn('Permission for notifications was denied')
} else {
console.error('Unable to subscribe to push', e)
}
}
}
return null
}
据我所理解,在安卓设备上,即使应用程序关闭了,服务工作者也应该在接收到推送通知时被唤醒。我需要编写特定的代码以确保服务工作者在需要时被唤醒吗?