Last active
March 18, 2019 19:29
-
-
Save Serginho/d734e5ca00799473f5f8fca85cf100fc to your computer and use it in GitHub Desktop.
push subscriptionchange upload token null
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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