Options of a PushSubscription

Published on Updated on

When a pushsubscriptionchange event occurs, it's an opportunity for a developer to re-subscribe the user for push. One of the pain points of this is that to re-subscribe a user, the developer has to keep the applicationServerKey (and any other subscribe() options) in sync between the web page's JavaScript and their service worker.

In Chrome 54 and later you can now access the options via the options parameter in a subscription object, known as PushSubscriptionOptions.

You can copy and paste the following code snippet into simple-push-demo to see what the options look like. The code simply gets the current subscription and prints out 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);
});

With this small piece of information you can re-subscribe a user in the pushsubscriptionchange event like so:

self.addEventListener('pushsubscriptionchange', e => {  
e.waitUntil(registration.pushManager.subscribe(e.oldSubscription.options)
.then(subscription => {
// TODO: Send new subscription to application server
}));
});

It's a small change, that will be super useful in the future.

Updated on Improve article

Back

DevTools Digest, September 2016 - Perf Roundup

Next

BroadcastChannel API - A message bus for the web

This site uses cookies to deliver and enhance the quality of its services and to analyze traffic. If you agree, cookies are also used to serve advertising and to personalize the content and advertisements that you see. Learn more about our use of cookies.