den-chan
den-chan

Reputation: 95

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

I have an (ideally) secure login object I would like to keep in a service worker context, yet ServiceWorkerGlobalScope appears to be reset at random (Chrome 47 Ubuntu).

To test, in the service worker I inserted:

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

And in the client:

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

Which resulted on the client console in:

⋮
147200.06500000003
148200.08000000002
149200.09000000003
1212.9800000000002
2212.5350000000003
3212.4700000000003
⋮

Unfortunately, I'm still unable to reliably replicate this.

As far as I know, a service worker should be removed from memory at some point after it's clients object no longer returns any Clients. However the above happens at least ten seconds removed from any deregistration event I can guess at.

So I have two questions. What could be causing this, and 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?

Upvotes: 1

Views: 1547

Answers (1)

Robert K. Bell
Robert K. Bell

Reputation: 10224

From 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.

So, Service Workers can only be relied on to keep their state long enough to handle an event. They definitely do not live as long as they are 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?

There is the Cache API.

Upvotes: 5

Related Questions