I have shipped three of these four strategies in production. The one I regret is the offscreen document, because it solved the visible problem while creating a hidden one: users could close a window and silently stop a background job they believed was running.
This is the ranking I would give a team starting today, with the trade-offs stated plainly.
Ranking criteria: does it survive a worker restart, does it keep sub-minute precision, how much code does it add, and what is the policy or maintenance risk?
4. Native timers plus keepalive
setInterval with a message every 20 seconds to hold the worker open.
- Survives restart: no.
- Precision: milliseconds while alive.
- Code cost: low to start, high to maintain.
- Risk: battery drain, reviewer scrutiny, and a false sense of durability. If the browser kills the worker during a long suspension, everything is still lost.
It ranks last because it does not solve persistence. It postpones the failure and makes it harder to reproduce.
3. Offscreen document
An offscreen document is a real DOM context. Timers there run at full resolution while the document exists.
- Survives restart: no, but the document can outlive worker restarts.
- Precision: milliseconds.
- Code cost: medium; lifecycle management, one document at a time, reasons in the manifest.
- Risk: the document can be closed by Chrome or the user, and using it purely as a keepalive is an abuse of the API.
It is the right tool for audio processing, clipboard access or DOM-dependent work. It is a poor answer to "my 10-minute timer keeps dying".
2. A build-time transform
If the extension already contains dozens of ordinary timer calls, rewriting them by hand is a migration project. A compiler can do it mechanically.
vite-mv3-sw-compile-persist analyzes the background entry with Babel, wraps long timers in alarm-backed implementations, marks mutated top-level state dirty and generates a runtime that restores it before handlers run.
- Survives restart: yes for marked state and long timers.
- Precision: alarm-limited (30 seconds minimum).
- Code cost: low at call sites, one build configuration.
- Risk: compiler edges. Destructuring is not persisted, anonymous callbacks that close over locals cannot be recovered, and
new Promise(r => setTimeout(r, …))remains fragile. Requires Vite 8+.
It ranks second only because it changes the build, not the runtime model. For an existing codebase, that is usually the cheapest correct move.
1. chrome.alarms plus a stored deadline
The boring winner.
- Survives restart: yes.
- Precision: approximate, 30-second floor.
- Code cost: one module, a handful of handlers.
- Risk: low. Alarms are the supported primitive for deferred work.
async function schedule(id: string, dueAt: number) {
await chrome.storage.local.set({ [`job:${id}`]: dueAt });
await chrome.alarms.create(`job:${id}`, { when: dueAt });
}
chrome.alarms.onAlarm.addListener(async ({ name }) => {
if (!name.startsWith('job:')) return;
const id = name.slice(4);
const key = `job:${id}`;
const stored = await chrome.storage.local.get(key);
if (!stored[key]) return;
await chrome.storage.local.remove(key);
await execute(id);
});
The important part is not the alarm call. It is the pair: an absolute deadline in storage and an idempotent executor. The alarm is a hint that the deadline may have arrived; storage decides whether the work is still pending.
The decision matrix
| Situation | Pick |
|---|---|
| One or two deferred jobs | Alarms plus deadline |
| Existing code with many timer call sites | Build-time transform |
| Audio, clipboard, DOM work while UI is closed | Offscreen document |
| Sub-minute tick with no UI open | Reconsider the feature |
| You are about to add a keepalive loop | Don't |
What none of them fix
No strategy gives exact scheduling. Chrome may delay alarms, batch wakeups and suspend the whole browser. If the product promise is "at 14:00 sharp", the promise is wrong; the implementable version is "at or shortly after 14:00, on the next wake".
Also, none of these survive the browser being closed. That requires storage.local plus catch-up logic on startup, which is a separate design decision from timer persistence.
The other constraint is the machine, not the API: a sleeping laptop does not fire alarms, and a suspended tab does not run timers. Every strategy above is bounded by whether the browser process is running at all.
With and without the plugin
The before/after from the plugin's README is the whole argument:
Without vite-mv3-sw-compile-persist
let count = 0;
chrome.action.onClicked.addListener(async () => {
const stored = await chrome.storage.session.get('count');
count = (stored.count as number) ?? 0;
count++;
await chrome.storage.session.set({ count });
});
chrome.alarms.create('cleanup', { delayInMinutes: 5 });
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'cleanup') cleanup();
});
With vite-mv3-sw-compile-persist
let count = 0;
chrome.action.onClicked.addListener(() => {
count++;
});
setTimeout(cleanup, 5 * 60_000);
The second version is the code you meant to write. The plugin adds restore, dirty tracking, a debounced flush and alarm-backed timers at build time — no runtime import, no wrapper API.
Repository: vite-mv3-sw-compile-persist
If you picked the last row of the matrix and want the build-time version, a star helps me keep the compiler honest.
Which row is your extension in today, and which one would you defend in a code review?
Top comments (2)
The ranking is right, and the offscreen-document regret is the most honest part — it solves the visible symptom while quietly handing the user a kill switch they don't know they're holding. The alarms-plus-stored-deadline pair is the boring winner for exactly that reason: the deadline in storage is the source of truth, the alarm is just the nudge. One edge I'm curious about: when the browser was closed and several deadlines pass, do you run every overdue job at startup, or coalesce them and skip the ones whose moment has passed? And with the build-time transform, if a timer was scheduled and the worker is killed, does the restored callback get its original due time, or does it recompute from the restore moment?
Agree on the offscreen document, a silent stop is worse than an honest limitation. One pattern that made the alarms approach much more robust for us: store the absolute deadline (Date.now() plus duration) in chrome.storage, never the remaining time. Every alarm handler and every cold worker start then recomputes from the deadline and catches up on whatever it missed. Alarms can fire late after the device sleeps, so a handler that assumes it ran on time drifts, while one that compares against the stored deadline corrects itself.