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
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
3 Answers
Reset to default 6Local 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 acplish 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();
...