最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to store a user id using service worker - Stack Overflow

programmeradmin1浏览0评论

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

Share Improve this question asked Oct 20, 2015 at 12:40 wazwaz 1,25318 silver badges33 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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 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();
...    
发布评论

评论列表(0)

  1. 暂无评论