extcharge

Guide

Keep state in a Manifest V3 service worker

1 December 2026

In a Manifest V3 extension, Chrome stops the service worker after 30 seconds without events, and every global variable is lost with it. Keep state in chrome.storage, schedule recurring work with chrome.alarms instead of setInterval, and cache server answers together with a timestamp so the extension can decide when to refresh and what to do offline.

This guide shows the lifecycle, picks the right storage area for each kind of data, and ends with a cache pattern you can copy.

Why does my service worker forget its variables?

The MV3 background script is an event-driven service worker, not a persistent page. Chrome starts it when an event arrives and terminates it when it has nothing to do. According to the Chrome documentation, termination happens:

Receiving an event or calling an extension API resets the idle timer. That keeps a busy worker alive, but you cannot count on it. The next time an event arrives, Chrome runs your script from the top. A counter, a cached token or a "loaded" flag held in a global variable is gone.

Two rules follow. First, treat globals as a cache that may be empty at any moment. Second, register every event listener synchronously at the top level of the script, not inside a function or after an await. Chrome dispatches the waking event right after the script runs, and a listener added later misses it.

Which chrome.storage area should I use?

The Web Storage API (localStorage) is not available in extension service workers. Use chrome.storage, which needs the storage permission and works from the service worker, the popup, the options page and content scripts.

Writes are asynchronous. Await them before you rely on the value elsewhere, and keep one key per concern so two parts of the extension do not overwrite each other's objects.

How do I run something every hour without setInterval?

setInterval and long setTimeout calls die with the worker. Use chrome.alarms instead, with the alarms permission. An alarm fires an onAlarm event, and Chrome wakes the service worker to deliver it. Older Chrome versions enforced a minimum period of one minute, later 30 seconds; check the current alarms reference for your target version. For cache refreshes you want minutes or hours anyway.

Two details matter. Alarms do not wake a sleeping device; missed alarms fire once when it wakes. And Chrome's own documentation recommends checking that important alarms exist each time the service worker starts, because persistence across browser restarts is not reliable in every version. The sample below does both.

How do I cache a server answer and refresh it?

Store the answer together with the time you got it. Every reader then compares the timestamp with a maximum age. Fresh enough: use it. Too old: fetch again. Fetch fails: fall back to the last answer, but only up to a hard limit.

// background.js (MV3 service worker, classic script)
const API_URL = "https://api.example.com/status";
const MAX_AGE_MS = 60 * 60 * 1000;           // refresh after 1 hour
const OFFLINE_LIMIT_MS = 3 * 24 * 60 * 60 * 1000; // trust old data up to 3 days

async function fetchStatus() {
  const res = await fetch(API_URL, { signal: AbortSignal.timeout(10000) });
  if (!res.ok) throw new Error("HTTP " + res.status);
  return res.json();
}

async function getStatus(force = false) {
  const { status } = await chrome.storage.local.get("status");
  const age = status ? Date.now() - status.checkedAt : Infinity;
  if (!force && age < MAX_AGE_MS) return status.value;
  try {
    const value = await fetchStatus();
    await chrome.storage.local.set({ status: { value, checkedAt: Date.now() } });
    return value;
  } catch (err) {
    // Offline or server error: use the last answer while it is not too old.
    return age < OFFLINE_LIMIT_MS ? status.value : null;
  }
}

async function ensureAlarm() {
  const alarm = await chrome.alarms.get("refresh-status");
  if (!alarm) await chrome.alarms.create("refresh-status", { periodInMinutes: 60 });
}

// Listeners: top level, registered synchronously.
chrome.runtime.onInstalled.addListener(ensureAlarm);
chrome.runtime.onStartup.addListener(ensureAlarm);
ensureAlarm(); // also on every service worker start
chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === "refresh-status") getStatus(true);
});
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.type !== "getStatus") return;
  getStatus().then(sendResponse);
  return true; // answer asynchronously
});

The manifest needs "permissions": ["storage", "alarms"] and, if your server does not send CORS headers for the extension origin, the API host in host_permissions. The popup asks for the value with chrome.runtime.sendMessage({ type: "getStatus" }), or reads chrome.storage.local directly if it only needs the cached copy.

The timeout on fetch keeps a slow server from holding the worker near its 30-second fetch limit.

What should happen when the extension is offline?

Decide this on purpose. The cached answer has two ages that matter:

  1. Max age. Below it, the answer is fresh and you skip the network. One hour is a reasonable start for data that changes rarely.
  2. Offline limit. Above max age but below this limit, a failed refresh still returns the old answer. Above it, the extension treats the answer as unknown and shows a neutral state, for example "Cannot reach the server. Retry."

A short offline limit means users lose features during an outage. A long one means stale data lives longer. Write the numbers down and use the same function everywhere, so the popup and the background never disagree.

Do it with your AI assistant

Paste this into Claude Code, Cursor or a similar coding assistant inside your extension's repository:

Read https://extcharge.com/guides/mv3-service-worker-state.html and apply it to this extension.

Adding payments

The same pattern is how an extension caches "has this user paid". A server holds the truth, and the extension keeps a timestamped copy so the popup answers fast and survives short outages. ExtCharge runs that server side for you: you connect your own Stripe account, and the extension asks extcharge.getUser() for the paid state. The one-prompt setup lets your AI assistant add it, and the integration guide covers the manifest and every call.

Try ExtCharge on your extension

Connect your Stripe account, register your extension and add a plan. The dashboard walks you through it.