如何使用 Service Worker 存储用户 ID

How to store a user id using service worker

有没有办法用 service worker 存储用户 ID 和其他可能的信息?

这样当您向它发送推送通知时,它就能够使用本地存储的信息并对其进行处理?

我尝试使用localStorage,但它似乎无法识别。

因为我得到这个错误:

Uncaught ReferenceError: localStorage is not defined

本地存储在 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 中不可用,尽管不幸的是它有一个更笨拙的东西 API。

最近想完成同样的事情。 IndexedDB 对于传递 UID 来说似乎太重了。但后来我意识到您可以通过服务工作者 url 路径中的查询参数传递 UID...

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

...然后只需在 Service Worker 中解析 location 即可访问它。

Service JS 中的 PARAMS 调用并在 Service Worker 中检索 self.location.search 中的值。

index.html

window.my_user_id = 16;

注册软件()

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

在 Service Worker 中,self.location.search 将包含值:?uid=16

保存订阅服务器:

 ....
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();
...