简体   繁体   中英

How to store a user id using service worker

Is there a way to store a user id and potentially other information with service worker?

So that when you send a push notification to it, it is able to use that locally stored information and do something with it?

I tried to use localStorage, but it doesn't seem to recognise it.

As I got this error:

Uncaught ReferenceError: localStorage is not defined

Local storage is not available in Service Workers because it does not have an asynchronous API . Service workers are designed to be fully async, so no synchronous APIs are available in a Service Worker context. You can use IndexedDB instead, although unfortunately it has a much clumsier API.

Wanted to accomplish the same thing recently. IndexedDB just seemed so heavy for just passing the UID. But then I realized you can pass a UID through query params in the service worker url path...

navigator.serviceWorker.register(`/public/js/lib/service-worker.js?uid=${window.uid}`).then((reg) => {

...then just access it by parsing location inside the service worker.

PARAMS en la llamda JS del servicio y recuperar el valor en self.location.search en service worker.

index.html

window.my_user_id = 16;

RegisterSW()

navigator.serviceWorker.register('PNServiceWorker.js?my_user_id='+window.my_user_id)

en el Service Worker, self.location.search contendra el valor: ?uid=16

Save Subscription Server:

 ....
if (self.location.search !== undefined) {
    body.params = self.location.search.substring(1);  // my_user_id=16        
}        
var fetchdata = {
        method: 'post',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
}
var response = await fetch(strSubscriberURL, fetchdata);
return await response.json();
...    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM