The feature request was one sentence: "send the welcome tip five minutes after install, not immediately". The implementation took twenty minutes. Making it survive a worker restart took an afternoon, because "five minutes later" is a promise the browser is not obligated to keep.
Here is the smallest design that does keep it.
What you need to know first: an alarm is a wakeup hint, not a job. The job lives in storage; the alarm only tells you when to look.
Step 1: model the task as data
Anything that must survive a restart has to be serializable. No closures, no class instances, no function references.
type DelayedTask = {
id: string;
dueAt: number; // absolute epoch ms
type: 'welcome-tip';
payload: { installId: string };
};
dueAt is absolute on purpose. If you store "five minutes from now" as a duration and re-evaluate it on every wake, the task drifts every time the worker restarts.
Step 2: persist before scheduling
Write the task first, then arm the alarm. If the worker dies between the two calls, the recovery pass can still find an unscheduled task; the reverse order loses work with no trace.
const QUEUE_KEY = 'delayed-tasks';
async function enqueue(task: DelayedTask) {
const stored = await chrome.storage.local.get(QUEUE_KEY);
const queue = (stored[QUEUE_KEY] ?? {}) as Record<string, DelayedTask>;
queue[task.id] = task;
await chrome.storage.local.set({ [QUEUE_KEY]: queue });
await chrome.alarms.create(`task:${task.id}`, { when: task.dueAt });
}
One key for the whole queue keeps writes cheap; one alarm per task keeps firing times independent.
Step 3: make the executor idempotent
Alarms can fire more than once, and a restart can create a second executor. Claim the task before running it.
async function claim(id: string): Promise<DelayedTask | null> {
const stored = await chrome.storage.local.get(QUEUE_KEY);
const queue = (stored[QUEUE_KEY] ?? {}) as Record<string, DelayedTask>;
const task = queue[id];
if (!task) return null;
delete queue[id];
await chrome.storage.local.set({ [QUEUE_KEY]: queue });
return task;
}
Removing before executing means a crash mid-task drops the job instead of repeating it. For a welcome tip that is correct. For a payment confirmation you would add a status: 'running' state and a retry budget instead of deleting outright. Choose the failure mode deliberately.
Step 4: handle the alarm
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (!alarm.name.startsWith('task:')) return;
const task = await claim(alarm.name.slice(5));
if (!task) return;
await runTask(task);
});
The !task branch is not defensive noise. It is the normal path when a duplicate alarm arrives after the first one already completed the work.
Step 5: recover on startup and install
Chrome does not guarantee that alarms survive every update or profile event. Rebuild them from the queue:
async function recover() {
const stored = await chrome.storage.local.get(QUEUE_KEY);
const queue = (stored[QUEUE_KEY] ?? {}) as Record<string, DelayedTask>;
const now = Date.now();
for (const task of Object.values(queue)) {
if (task.dueAt <= now) {
const claimed = await claim(task.id);
if (claimed) await runTask(claimed);
} else {
await chrome.alarms.create(`task:${task.id}`, { when: task.dueAt });
}
}
}
chrome.runtime.onStartup.addListener(() => void recover());
chrome.runtime.onInstalled.addListener(() => void recover());
This is also the catch-up path for a browser that was closed past the due time. The task runs at the next opportunity, once.
Step 6: prove it with a kill test
Open chrome://serviceworker-internals, enqueue a task due in two minutes, stop the worker, wait, and watch. Then enqueue one due in ten seconds, stop the worker, and reopen the extension. Both paths should produce exactly one execution.
Where the design leaks
Alarms have a 30-second floor and approximate firing, so a task due in five seconds may run in thirty. If the browser is closed at the deadline, nothing runs until it opens again; "five minutes after install" becomes "five minutes after install, or at the next launch". And storage writes are not transactional across keys, so multi-task updates need either a single queue key, as above, or a version field to detect lost updates.
vite-mv3-sw-compile-persist can generate the state-restore part of this pattern from ordinary variables, but it will not design your idempotency for you. That part stays human.
One more detail: Date.now() follows the system clock, so a user changing their clock can move a deadline. That is acceptable for reminders and not acceptable for billing; store a server timestamp when the exact moment matters.
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 your queue needs to survive a restart, star the repo and steal the claim-before-run pattern even if you never install the plugin.
What is the worst thing your extension could do twice if an alarm fired at the wrong moment?
Top comments (0)