Skip to content

Instantly share code, notes, and snippets.

@Serginho
Last active March 18, 2019 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Serginho/d734e5ca00799473f5f8fca85cf100fc to your computer and use it in GitHub Desktop.
Save Serginho/d734e5ca00799473f5f8fca85cf100fc to your computer and use it in GitHub Desktop.
push subscriptionchange upload token null
// To use IndexedDB like localStorage use this library.
// https://github.com/RyotaSugawara/serviceworker-storage
const storage = new ServiceWorkerStorage('sw:storage', 1);
async handlePush() {
const newSubscription = await self.registration.pushManager.getSubscription();
const oldSubscription = JSON.parse(await storage.getItem('subscription'));
if(newSubscription.endpoint !== oldSubscription.endpoint) {
storage.setItem('subscription', newSubscription);
const req = new Request('/refreshpushsubscription', {
method: 'POST',
body: JSON.stringify(
{oldSubscription: oldSubscription, newSubscription: newSubscription})
});
const response = await self.fetch(req);
}
}
async savePush(subscription: PushSubscription) {
await storage.setItem('subscription', subscription);
}
self.addEventListener('pushsubscriptionchange', (event: PushSubscriptionChangeEvent) =>
event.waitUntil(handlePush()));
// Listen messages from browser and wait for the first subscription to save it for
// future expirations.
self.addEventListener('message', (event) => {
if(event.data.action === 'REQUEST_SUBSCRIPTION') {
event.waitUntil(savePush(event.data.subscription));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment