Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 ยท Projects and Practice

Project: Tab Snoozer with Alarms and Notifications

Build a tab snoozer that closes a tab and reopens it later using chrome.alarms, chrome.storage and a service worker that survives restarts, with a testable scheduling core and a store-ready checklist.

Too many tabs? Tab Snoozer closes the current tab, remembers its address and opens it again at a time you choose. The project is a showcase for the service worker rules you learned: it may be stopped at any moment, so everything it needs lives in chrome.storage, and timing is handled by chrome.alarms, never by setTimeout.

The extension needs Chrome. The scheduling core is plain JavaScript and runs below; the Chrome code is shown for copying.

Why alarms and not setTimeout

A timer created with setTimeout lives in worker memory. When Chrome stops the idle worker (after about 30 seconds), the timer disappears and the snooze is lost. chrome.alarms is stored by the browser: it fires even if the worker was stopped, and wakes it up with an alarms.onAlarm event. Alarms need the "alarms" permission, and the minimum period is 30 seconds in recent Chrome versions.

sequenceDiagram
    participant U as User
    participant P as Popup
    participant W as Service worker
    participant S as Storage
    participant A as Alarms
    U->>P: Snooze 1 hour
    P->>W: message (url, title, minutes)
    W->>S: save snooze entry
    W->>A: create alarm "snooze:id"
    W->>U: close tab
    A-->>W: onAlarm (even after a restart)
    W->>S: read entry by id
    W->>U: open tab, remove entry

State lives in storage and the alarm; the worker can sleep in between.

Files and permissions

JSON
{
  "manifest_version": 3,
  "name": "Tab Snoozer",
  "version": "1.0.0",
  "description": "Close a tab now and have it reopen later.",
  "permissions": ["tabs", "storage", "alarms"],
  "action": { "default_popup": "popup.html" },
  "background": { "service_worker": "service-worker.js" }
}

tabs is needed to read the tab's URL and title; if you only snooze the tab the user clicked on, activeTab would be enough and removes the install warning. See Permissions model.

The scheduling core

JavaScript
// snooze.js (pure logic)
export function addSnooze(snoozes, { url, title }, minutes, now = Date.now()) {
  const id = `${now}-${Math.random().toString(36).slice(2, 7)}`;
  return {
    id,
    snoozes: { ...snoozes, [id]: { url, title, wakeAt: now + minutes * 60000 } }
  };
}

export function dueSnoozes(snoozes, now = Date.now()) {
  return Object.entries(snoozes)
    .filter(([, s]) => s.wakeAt <= now)
    .map(([id, s]) => ({ id, ...s }));
}

export function removeSnooze(snoozes, id) {
  const { [id]: _gone, ...rest } = snoozes;
  return rest;
}
Run the scheduling core

The functions take now as a parameter, so a test does not have to wait: it passes any time it likes (Unit testing).

The service worker

JavaScript
// service-worker.js
import { addSnooze, dueSnoozes, removeSnooze } from "./snooze.js";

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message?.type !== "snooze") return;
  if (sender.id !== chrome.runtime.id) return;
  if (!Number.isFinite(message.minutes) || message.minutes < 1 || message.minutes > 10080) return;

  (async () => {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tab?.url || !/^https?:/.test(tab.url)) return sendResponse({ ok: false });

    const { snoozes = {} } = await chrome.storage.local.get("snoozes");
    const result = addSnooze(snoozes, tab, message.minutes);
    await chrome.storage.local.set({ snoozes: result.snoozes });
    await chrome.alarms.create(`snooze:${result.id}`, { delayInMinutes: message.minutes });
    await chrome.tabs.remove(tab.id);
    sendResponse({ ok: true });
  })();
  return true;                                   // async reply
});

chrome.alarms.onAlarm.addListener(async (alarm) => {
  if (!alarm.name.startsWith("snooze:")) return;
  const { snoozes = {} } = await chrome.storage.local.get("snoozes");
  const id = alarm.name.slice("snooze:".length);
  const entry = snoozes[id];
  if (!entry) return;
  await chrome.tabs.create({ url: entry.url });
  await chrome.storage.local.set({ snoozes: removeSnooze(snoozes, id) });
});

Important details:

  • Every listener is registered at the top level, so a waking worker sees it.
  • The listener validates sender and message (Secure messaging).
  • The reply is asynchronous, so the listener returns true (One-time messages).
  • The popup is a few buttons ("1 hour", "Tonight", "Tomorrow") that send { type: "snooze", minutes }.

Recovering from a missed alarm

If the computer was asleep or Chrome was closed at the alarm time, the alarm fires when Chrome next runs. For safety, also check on startup:

JavaScript
chrome.runtime.onStartup.addListener(async () => {
  const { snoozes = {} } = await chrome.storage.local.get("snoozes");
  for (const due of dueSnoozes(snoozes)) {
    await chrome.tabs.create({ url: due.url, active: false });
    delete snoozes[due.id];
  }
  await chrome.storage.local.set({ snoozes });
});

Ship it

Before submitting (Preparing for the store): replace tabs with activeTab if possible, add icons and a privacy policy (the extension stores page URLs locally, which counts as web history), and write the justification for alarms ("reopens snoozed tabs at the time the user selected").

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use chrome.alarms instead of setTimeout for snoozing?

    Timers die with the worker. Alarms persist and wake it with onAlarm.
  2. 2. Where is the snoozed tab's address kept until it reopens?

    The worker has no reliable memory, so entries live in storage and the alarm name carries the id.
  3. 3. Why does the onMessage listener return true?

    Returning true keeps the response channel open for sendResponse after async calls.
  4. 4. Why pass now as a parameter in the scheduling functions?

    Injecting time lets tests simulate hours in a few milliseconds.

Summary

  • Service workers sleep, so use chrome.alarms plus chrome.storage for anything scheduled.
  • Register listeners at the top level and validate every message.
  • Keep logic in pure functions that take now, and keep Chrome calls thin.
  • Recover on startup and minimise permissions before publishing.

Next: Practice: Extension Challenges