是什么导致服务工作者的全局上下文被重置?

What causes the global context of a service worker to be reset?

我有一个(理想情况下)安全登录对象,我想保留在服务工作者上下文中,但 ServiceWorkerGlobalScope 似乎是随机重置的 (Chrome 47 Ubuntu)。

为了测试,在我插入的 service worker 中:

var iid = setInterval(function () {
  var now = performance.now();
  return self.clients.matchAll().then(function(clients) {
    return Promise.all(clients.map(function(client) {
      return client.postMessage({messageType: "canary", value: now})
    }))
  })
}, 1000);

并且在客户端中:

navigator.serviceWorker.addEventListener("message", function(event) {
  if (event.data.messageType = "canary") console.log(event.data.value)
});

在客户端控制台上的结果为:

⋮
147200.06500000003
148200.08000000002
149200.09000000003
1212.9800000000002
2212.5350000000003
3212.4700000000003
⋮

不幸的是,我仍然无法可靠地复制它。

据我所知,服务工作者应该在 clients 对象不再 returns 任何 Client 之后的某个时刻从内存中删除。然而,上述情况发生在我能猜到的任何注销事件至少十秒后。

所以我有两个问题。是什么导致了这种情况,在不序列化且最好不发送到客户端上下文的情况下将对象持久化为与服务工作者脚本关联的最佳实践是什么?

来自the spec:

The lifetime of a service worker is tied to the execution lifetime of events, not references held by service worker clients to the ServiceWorker object. The user agent may terminate service workers at any time it has no event to handle or detects abnormal operation such as infinite loops and tasks exceeding imposed time limits, if any, while handling the events.

因此,只能依靠 Service Worker 将其状态保持足够长的时间来处理事件。他们肯定活不了多久registered with clients.


what would be best practises for persisting an object as associated with a service worker script, without serialising and preferably without sending to a client context?

the Cache API.