发生 pushsubscriptionchange
事件时,开发者有机会重新订阅用户以进行推送。这样做的其中一个痛点是,如需重新订阅用户,开发者必须使 applicationServerKey
(以及任何其他 subscribe()
选项)在网页的 JavaScript 与其 Service Worker 之间保持同步。
在 Chrome 54 及更高版本中,您现在可以通过订阅对象(称为 PushSubscriptionOptions)中的选项参数访问选项。
您可以将以下代码段复制并粘贴到 simple-push-demo 中,查看各选项的显示效果。该代码会获取当前订阅并输出 subscription.options
。
=======
navigator.serviceWorker.ready.then(registration => {
return registration.pushManager.getSubscription();
})
.then(subscription => {
if (!subscription) {
console.log('No subscription 😞');
return;
}
console.log('Here are the options 🎉');
console.log(subscription.options);
});
利用这部分信息,您可以在 pushsubscriptionchange 事件中重新订阅用户,如下所示:
self.addEventListener('pushsubscriptionchange', e => {
e.waitUntil(registration.pushManager.subscribe(e.oldSubscription.options)
.then(subscription => {
// TODO: Send new subscription to application server
}));
});
这是一个很小的更改,将来会非常有用。