Skip to main content
InterviewHubPRO
Section Overview
Q37

Question 37 of 536

Part 1: Core Objects, Prototypes, Functions & Scope (1 - 53)

7%
JavaScript & V8 Internals (536 Qs)•Part 1: Core Objects, Prototypes, Functions & Scope (1 - 53)

How do you reuse information across service worker restarts

mid LevelMost AskedCode ExampleFormsPrototypesHTTP & REST APIs

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