JavaScript Internals (521 Qs)•Part 1: Core Objects, Prototypes, Functions & Scope (1 - 53)
How do you reuse information across service worker restarts
The problem with service worker is that it gets terminated when not in use, and restarted when it's next needed, so you cannot rely on global state within a service worker's onfetch and onmessage handlers. In this case, service workers will have access to IndexedDB API in order to persist and reuse across restarts.
Practical Code Example
javascript
// Service Workers are terminated when idle. Global variables are wiped on restart.
// To persist state across restarts, use IndexedDB or CacheStorage:
// Inside Service Worker (sw.js)
async function persistState(key, val) {
const cache = await caches.open('sw-state-cache');
await cache.put(new Request(key), new Response(JSON.stringify(val)));
}
async function getState(key) {
const cache = await caches.open('sw-state-cache');
const response = await cache.match(new Request(key));
return response ? await response.json() : null;
}