meteor - Secure, resilient resubscription for push notifications in service workers -
i attempting implement service worker performs push notifications web app. i'd system resilient in keeps sending push notifications without user needing regularly interact app. end, i'm eyeing pushsubscriptionchange event, not sure how work within service worker's limited constraints.
method 1: post app
my current code captures event, creates new subscription , sends client via postmessage. client calls back-end , registers new subscription endpoint.
this seems elegant way, except assume require open tab. if user doesn't check in few days still interested in getting push notifications, existing subscription time out, , there no way notify app newly-acquired endpoint.
method 2: securely call rest endpoint
i had idea add rest endpoint app accepts updated subscription. 1 complication app uses meteor, there's substantial bit of own infrastructure (the ddp protocol, instance) service workers don't have access to.
my thought generate uuid token whenever new subscription added. service workers fetch endpoint passing token query parameter , sending new endpoint/key. new token created, old 1 deleted, , new push endpoint registered.
unfortunately, i'm not sure how store token in way clients , service workers share. local storage isn't available service workers. cache api seems targeted @ actual requests, not @ simple key/values. indexdb available service workers, literally want store uuid keyed off of "pushendpointtoken". have no other option opening database , declaring schema single key/value?
is there third method i'm not considering? want ensure app has valid push endpoint long user wants receive notifications it.
thanks.
update
runtime variables lost when service worker stopped , woken later. need use persistent storage such indexeddb or cookies (to append token requests).
i can recommend idb-keyval - i'm sharing 1 database between app (write) , service worker (read).
old answer:
you can use postmessage api send token service worker concept, i'm still working on it
service-worker.js:
const runtimevars = { token: undefined, } self.addeventlistener('message', event => { // no need check if (event.origin !== self.origin) { return } if (event.data.token) { runtimevars.token = event.data.token } }) self.addeventlistener('pushsubscriptionchange', event => { // fire unregister request runtimevars.token }) app.js
const controller = window.navigator.serviceworker.controller if (controller) // @ app dispatch controller.postmessage({token: localstorage.getitem('token'}) // after login pass api token service worker controller.postmessage({token}) // after logout, nullify token controller.postmessage({token: undefined}) }
Comments
Post a Comment