Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Background Service Workers

Events, Alarms and the Badge

Handle browser events with filters, schedule repeating work with chrome.alarms, update the toolbar badge, and use offscreen documents when a service worker needs a DOM.

The service worker's job is to respond to events. In this lesson you will meet the most useful ones, learn how to filter them so your worker wakes up less, schedule repeating work with alarms, and show information on the toolbar icon with the badge.

How events work

Every chrome.* API that can notify you exposes events with addListener, removeListener and hasListener:

JavaScript
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === "complete") {
    console.log("Finished loading:", tab.url);
  }
});

Common events:

Event Fires when
runtime.onInstalled The extension is installed or updated
runtime.onStartup A browser profile starts with the extension enabled
runtime.onMessage A message arrives from another part
tabs.onCreated, onRemoved, onActivated, onUpdated Tab changes
windows.onFocusChanged The focused window changes
action.onClicked The toolbar icon is clicked (no popup set)
commands.onCommand A shortcut from the manifest is pressed
alarms.onAlarm An alarm goes off
idle.onStateChanged The user becomes idle, locked or active
downloads.onChanged A download changes state
webNavigation.onCompleted A page navigation finishes

Some events accept filters so Chrome only wakes you for relevant ones:

JavaScript
chrome.webNavigation.onCompleted.addListener(
  (details) => { /* only example.com pages */ },
  { url: [{ hostSuffix: "example.com" }] }
);

Filtering at the source is cheaper than waking the worker for every navigation and discarding most.

Alarms

An alarm is a scheduled wake-up that survives the worker stopping. You need the "alarms" permission.

JavaScript
// once, in 5 minutes
chrome.alarms.create("remind", { delayInMinutes: 5 });

// every 30 minutes, first time in 1 minute
chrome.alarms.create("poll", { delayInMinutes: 1, periodInMinutes: 30 });

chrome.alarms.onAlarm.addListener((alarm) => {
  console.log("Alarm fired:", alarm.name, new Date(alarm.scheduledTime));
});

Facts worth knowing:

  • Since Chrome 120, the minimum period is 30 seconds (it was 1 minute); an alarm may fire slightly late, never early.
  • Alarms persist while Chrome is running, but may not survive a browser restart, so recreate them in onInstalled and onStartup, after checking chrome.alarms.get(name) so you do not reset a running schedule.
  • A name is unique: creating an alarm with an existing name replaces it.
  • Other methods: getAll(), clear(name), clearAll().
JavaScript
async function ensureAlarm() {
  const existing = await chrome.alarms.get("poll");
  if (!existing) chrome.alarms.create("poll", { periodInMinutes: 30 });
}
chrome.runtime.onInstalled.addListener(ensureAlarm);
chrome.runtime.onStartup.addListener(ensureAlarm);

The badge

The badge is the small text on top of the toolbar icon, good for a counter or a status.

JavaScript
chrome.action.setBadgeText({ text: "12" });                 // all tabs
chrome.action.setBadgeText({ text: "ON", tabId });         // one tab
chrome.action.setBadgeBackgroundColor({ color: "#2563eb" });
chrome.action.setBadgeTextColor({ color: "#ffffff" });
chrome.action.setTitle({ title: "12 unread items" });      // tooltip

The badge holds about four characters; an empty string removes it. Set tabId to show per-tab values, which reset when the tab navigates.

sequenceDiagram
    participant A as chrome.alarms
    participant W as Service worker
    participant S as chrome.storage
    participant B as Badge
    A->>W: onAlarm("poll")
    W->>W: fetch new data
    W->>S: save { unread: 3 }
    W->>B: setBadgeText("3")

An alarm wakes the worker, which updates the badge and exits.

A polling extension, simulated

This stand-in model has a fake clock, a fake alarm API, fake storage and a fake badge. Alarm logic is real, only the clock is accelerated. It shows how the pieces connect: create the alarm, handle onAlarm, update storage and the badge.

JS Alarm-driven badge counter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Debouncing noisy events

Some events fire in bursts (tabs.onUpdated fires several times per page load, storage.onChanged once per key). Debounce with an alarm or compare state so you do only one piece of work:

JS Collapse a burst of events

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In a worker, remember that setTimeout is lost if the worker stops. A short debounce (under a few seconds) is safe; for anything longer use chrome.alarms.

Offscreen documents

When the worker needs a DOM (play a sound, parse HTML with DOMParser, use the clipboard, run a canvas), ask Chrome for a hidden extension page:

JavaScript
await chrome.offscreen.createDocument({
  url: "offscreen.html",
  reasons: ["AUDIO_PLAYBACK"],
  justification: "Play a chime when the timer ends",
});
chrome.runtime.sendMessage({ type: "play-chime" });

Needs the "offscreen" permission. Only one offscreen document can exist at a time, and each needs a declared reason (AUDIO_PLAYBACK, DOM_PARSER, CLIPBOARD, BLOBS, and others). Close it with chrome.offscreen.closeDocument() when finished.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why prefer chrome.alarms over setInterval in the service worker?

    Timers live in worker memory and vanish when the worker stops. Alarms are managed by Chrome.
  2. 2. What is the smallest period you can use for a repeating alarm in current Chrome?

    Since Chrome 120 the minimum is 30 seconds.
  3. 3. What should you do in both onInstalled and onStartup for alarms?

    Alarms may not survive a browser restart, so ensure they exist, checking first so you do not reset a running schedule.
  4. 4. How do you show a number on the toolbar icon?

    setBadgeText sets the short text overlay; use an empty string to clear it.

Summary

  • Listen to events at the top level; use filters to avoid unnecessary wake-ups.
  • Alarms (alarms permission) schedule work that survives worker restarts.
  • Recreate alarms in onInstalled and onStartup if missing.
  • The badge shows up to about four characters and can be set per tab.
  • Offscreen documents give the worker a DOM when it truly needs one.

Next: Context Menus and Notifications