Skip to content

Chrome Extension Analytics: Service Worker or Content Script?

6 min readModerok team

Chrome extension analytics in a content script or the background service worker: which context reaches your endpoint, survives a flush, and sees installs.

Send analytics from the background service worker, and relay events to it from your popup, options page and content scripts with chrome.runtime.sendMessage. The reason is not taste. A content script's requests carry the origin of whatever page it was injected into, a popup's document is thrown away the moment the popup closes, and a content script runs once per matching tab, so the same counter exists in a dozen places at once. Only the background service worker has all three of the properties analytics needs: a single instance, your extension's own origin, and the install and update events.

TL;DR: Initialize your analytics SDK and call track() in the background service worker. Use content scripts and UI pages only to gather facts that exist nowhere else, and pass those to the worker as a message. Expect the worker to be killed mid-flush, so queued events belong in chrome.storage.

The 30-second comparison

Background service workerContent scriptPopup or options page
Origin of its requestsThe extension's own originThe page's: requests go "on behalf of the web origin that the content script has been injected into" (Chrome)The extension's own origin
Can host_permissions exempt it from CORS?Yes: For listed hostsNo: "Cross-origin requests are always treated as such in content scripts, even if the extension has host permissions" (Chrome)Yes: For listed hosts
Extension APIs reachableAll APIs the manifest permitsOnly dom, i18n, storage, runtime.connect(), runtime.getManifest(), runtime.getURL(), runtime.id, runtime.onConnect, runtime.onMessage, runtime.sendMessage() (Chrome: content scripts)All APIs the manifest permits
How it dies"After 30 seconds of inactivity", though "receiving an event or calling an extension API resets this timer" (Chrome)With the page, on navigation or tab close"unloaded every time the popup is closed" (MDN)
How many copies runOneOne per matching frame; all_frames "defaults to false, meaning that only the top frame is matched" (Chrome)One, while open
Sees install and updateYes: runtime.onInstalled fires on first install, on extension update, and on a Chrome update (Chrome)NoNo

Round 1Can a content script reach your analytics endpoint?

This is where most content-script analytics setups quietly fail. Chrome's networking documentation says a content script's requests belong to the page, and that "cross-origin requests are always treated as such in content scripts, even if the extension has host permissions." So the Origin on an event POST is one site on this tab and another on the next, and success depends on what your endpoint returns in Access-Control-Allow-Origin for each. host_permissions does not help: that exemption is for extension contexts, not a script inside a page. We covered the error itself in why a Chrome extension fetch gets blocked by CORS policy.

From the service worker, the request carries your extension's own chrome-extension:// origin instead, on every tab, so there is one CORS outcome to get right rather than one per site.

Winner

The service worker.

Round 2Which context is still alive when the request lands?

A flush is an async POST, so the context has to live long enough to see the response and retry. The popup does not. MDN states that a popup's document "is loaded every time the popup is shown, and unloaded every time the popup is closed," and users close popups by clicking elsewhere, often a second after pressing the button you are counting. A content script survives only as long as its page: one navigation and the event queued in a module-level array is gone.

The service worker is not immortal either, but its death is documented and survivable. Chrome terminates it "after 30 seconds of inactivity," where "events and calls to extension APIs reset these timers," and also "when a fetch() response takes more than 30 seconds to arrive," so a slow analytics endpoint can take the worker down with it. The difference is that an incoming event revives the worker, so work parked in chrome.storage.local gets another attempt. The Moderok SDK's queue is capped and debounced, and retryable failures are persisted and retried with backoff. No queue makes a terminated worker lossless. More on surviving restarts: why your extension's service worker keeps stopping.

Winner

The service worker, as long as the queue is persisted rather than remembered.

Round 3How many copies of your counter are running?

all_frames "defaults to false, meaning that only the top frame is matched," so the usual content script is one instance per matching tab rather than per iframe. Say a user has twelve matching tabs open. That is twelve independent copies of your analytics state: twelve in-memory session flags, twelve "first run today" checks, twelve read-modify-write cycles against one chrome.storage.local key, with no ordering between them. Session counts inflate, daily flags get clobbered.

Your extension has one background service worker: one writer for counters, daily flags and queue state.

Winner

The service worker.

Round 4What can each context actually see?

The worker wins the previous three rounds and loses this one. It has no DOM, no window, and no idea which element the user clicked. Lifecycle facts, though, exist nowhere else: in Chrome's documented ordering, runtime.onInstalled arrives between the install and activate service worker events. That is why install and update tracking has to be registered in the worker at the top level, before any await. Two of Moderok's automatic events, __install and __update, come from that listener, and the initialization guide is blunt about the cost of deferring init(): "If init() runs after async work, you can miss __install and __update events."

Winner

Split. Lifecycle events belong to the worker, page-level detail belongs to the content script.

When a content script is the right place to gather the analytics event

If the fact you want only exists in the page, the content script is not a compromise, it is the only option. How many matches your selector found, whether the site rendered the layout your feature depends on, which supported host the user ran it on: none of that is visible from the worker, and a bare feature_used event throws away the part you needed.

So measure in the page and send from the worker. Content scripts can use runtime.sendMessage() and storage directly, per Chrome's list above, which is all a relay needs.

The analytics pattern: gather in the content script, track from the service worker

The Moderok SDK has no message bus of its own, as the patterns guide says, so you write the relay. It is short.

In the content script, popup or options page:

chrome.runtime.sendMessage({
  type: "analytics",
  name: "highlight_applied",
  properties: { matches: 12, host_class: "docs" },
});

In the background service worker:

import { Moderok } from "@moderok/sdk";

Moderok.init({ appKey: "mk_your_app_key" });

const ALLOWED = new Set(["highlight_applied", "export_clicked", "settings_saved"]);

chrome.runtime.onMessage.addListener((message, sender) => {
  if (sender.id !== chrome.runtime.id) return;
  if (message?.type !== "analytics") return;
  if (!ALLOWED.has(message.name)) return;
  Moderok.track(message.name, message.properties);
});

Three details are doing real work. Moderok.init() is at the top level, before any await, so the install and update listeners register on the first run. The sender.id check keeps the handler to your own contexts. The name allowlist matters because a content script shares a tab with code you do not control, and Chrome's networking guidance warns against letting content scripts drive privileged requests: "do not allow content scripts to request an arbitrary URL." The same caution applies to your reports. Properties stay flat: only strings, finite numbers and booleans survive.

You can also track from a UI page directly: each context gets its own SDK instance, and if the background has already initialized, calling track() first makes the SDK load the saved config from chrome.storage.local and initialize itself. But Round 2 applies. The SDK flushes on a timer and when batches fill, so an event tracked in a popup that closes a moment later may never leave that context, and Moderok.flush() is itself async. Relaying to the worker avoids the question.

Moderok is an analytics SDK built for this shape of problem: 5.7 kB gzipped, zero runtime dependencies, install and update events without a track() call. The patterns guide has the background-only setup, and the product page shows the reports.