Skip to content

Chrome Extension Session Tracking: Measuring Session Length in MV3

7 min readModerok team

A Chrome extension has no built-in session. How to define and measure session length from an MV3 service worker, and when to count active days instead.

If session length is on your checklist while you pick an analytics tool for a browser extension, start here: no tool can report it as a platform fact. An extension has no page load to open a session and no shutdown hook you can rely on to close one. Chrome's lifecycle documentation makes the point in passing, explaining why an extension service worker's activate event fires immediately after installation: "there is nothing comparable to a page reload in an extension" (service worker lifecycle). Any session length for an extension is therefore a number somebody defined. What you are really choosing is whether you can define it yourself, and whether the tool will count what you send. This post covers the three workable definitions, the code for each, and when session length is the wrong metric to chase.

TL;DR: Keep a lastSeen timestamp and a session id in chrome.storage.session, start a new session when the gap since the last tracked interaction exceeds a threshold you choose, and report the finished session's length when the next one starts. Treat the result as a definition, not a measurement. The only duration you can observe directly is how long one of your own UI surfaces was open, and even that is a floor: the worker can be terminated before the close is recorded.

Why chrome extension session tracking has nothing to anchor to

Three platform facts do the damage, all on Chrome's service worker lifecycle page.

The service worker is not alive for the length of a session. That page says Chrome normally terminates it "after 30 seconds of inactivity", when a single request takes longer than five minutes, or when a fetch() response takes more than 30 seconds to arrive, and that receiving an event or calling an extension API resets the timer. Since Chrome 110, "all events reset the idle timer and the idle timeout will not occur if there are pending events" (longer extension service worker lifetimes), which helps during a burst of work and changes nothing about a user who walks away for ten minutes.

In-memory state does not survive. The same lifecycle page warns that "Any global variables you set will be lost if the service worker shuts down," so a sessionStart variable in module scope is the wrong place for session state.

Termination is not an event you can count. The guidance on that page is to "design your service worker to be resilient against unexpected termination," not to hook the shutdown. There is no reliable callback to fire a session_end event from.

The store reports do not fill the gap either. Chrome's Web Store metrics page documents install and uninstall reports, impressions, and weekly user retention, and notes that the "Users stats only captures installations; it doesn't monitor whether users are active or not." There is no time-in-extension figure to compare your own number against.

The three definitions of a session, and what each one costs

DefinitionBoundaryObservable?
Interaction gapA new session starts when the gap since the last tracked interaction exceeds a threshold you pickDerived from timestamps you store
Browser runA new session starts the first time your code runs after a browser restartchrome.storage.session is cleared when the browser restarts (storage)
UI surface openA popup or side panel is opened and closedObservable from a port's onDisconnect (messaging)

The gap rule is what most teams mean by "session." Note what it measures: the spacing of the events you chose to track. Track fewer events and your sessions get shorter, with no change in user behaviour.

Implementing the gap rule

chrome.storage.session is the right home for this. Chrome's storage reference says session storage "holds data in memory while an extension is loaded" and "is cleared if the extension is disabled, reloaded, updated, and when the browser restarts", with a storage limit of "10 MB (1 MB in Chrome 111 and earlier)". That clearing behaviour is a feature here: a browser restart ends the session for you, which is usually what you want, and the data never lands on disk.

const SESSION_GAP_MS = 30 * 60 * 1000; // your choice, not a platform value

async function touchSession(now = Date.now()) {
  const prev = await chrome.storage.session.get(["sessionId", "startedAt", "lastSeen"]);
  const isNew = !prev.sessionId || !prev.lastSeen || now - prev.lastSeen > SESSION_GAP_MS;

  if (!isNew) {
    await chrome.storage.session.set({ lastSeen: now });
    return { id: prev.sessionId, isNew: false, closedMs: null };
  }

  const id = crypto.randomUUID();
  await chrome.storage.session.set({ sessionId: id, startedAt: now, lastSeen: now });
  const closedMs = prev.startedAt && prev.lastSeen ? prev.lastSeen - prev.startedAt : null;
  return { id, isNew: true, closedMs };
}

The finished session reports itself when the next one opens, which is the only moment you can be sure it ended. The cost is that the last session before a browser close is never reported, because session storage is gone by the time your code runs again. Mirror the three keys into chrome.storage.local if you would rather pay for disk writes than lose that tail.

chrome.storage.session needs the storage permission and nothing more, the same permission an analytics SDK already asks for (see what permissions Chrome extension analytics needs). Two events arriving close together can both read the old lastSeen before either writes, so serialise the calls through one promise chain if a double session_start would bother you.

The reporting trap: names are counted, properties are not

This is the part that decides whether session tracking is worth your time. In Moderok's dashboard the custom event name is the unit that gets counted. Properties travel with the event and appear in the raw event context, but they are not chart breakdowns, so a session_id property does not produce an average session length chart, and neither does a duration_ms property.

If you want session length visible without building your own query layer, put the bucket in the name:

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

function bucket(ms) {
  const s = Math.round(ms / 1000);
  if (s < 10) return "0_10s";
  if (s < 60) return "10_60s";
  if (s < 300) return "1_5m";
  return "5m_plus";
}

async function trackInSession(name, properties = {}) {
  const { id, isNew, closedMs } = await touchSession();
  if (closedMs !== null) Moderok.track(`session_length_${bucket(closedMs)}`);
  if (isNew) Moderok.track("session_start");
  Moderok.track(name, { ...properties, session_id: id });
}

Four event names, four counts you can read as a distribution. session_id rides along as a property, and Moderok's property rules are flat values only: strings, numbers and booleans, with nested objects and arrays dropped (events and properties). The bucketing is coarse on purpose: the underlying number was a definition anyway.

The one duration you can actually observe

A popup or side panel is a real document that loads and unloads, so you can time it from the service worker with a port. Chrome's messaging documentation lists the causes of onDisconnect, among them that "the frame where connect() was called has unloaded."

In the popup:

chrome.runtime.connect({ name: "popup" });

In the service worker, at the top level:

chrome.runtime.onConnect.addListener((port) => {
  if (port.name !== "popup") return;
  const opened = Date.now();
  port.onDisconnect.addListener(() => {
    Moderok.track(`popup_open_${bucket(Date.now() - opened)}`);
  });
});

Three caveats, all documented. The messaging page warns that onDisconnect "may fire more than once" when a port has multiple receivers, so guard against a double count. The lifecycle page records that from Chrome 114, "Sending a message with long-lived messaging keeps the service worker alive. Opening a port no longer resets the timers," so a silently open popup does not protect the worker from the 30 second idle rule and some closes will never be recorded. And an in-memory opened constant dies with the worker, so persist it to chrome.storage.session if you want the longer opens to survive. Treat the resulting numbers as a floor.

chrome.idle does not measure time in your extension

It is tempting to reach for chrome.idle here. Read what it returns: the idle reference says queryState(detectionIntervalInSeconds) returns "locked" if the system is locked, "idle" if the user has not generated any input for a specified number of seconds, or "active" otherwise, and that the default detection interval behind onStateChanged is 60 seconds. That is the state of the machine, not of your extension. A user typing in another tab for an hour counts as active throughout. It also needs its own idle permission, a real cost for a signal that cannot tell your extension apart from everything else on screen.

When to skip session length entirely

If the question behind "how long are sessions" is "are people getting value," distinct active days and actions per active day answer it better and do not rest on a threshold you invented. A once-per-day heartbeat gives you daily, weekly and monthly actives with no session rule at all, which is the approach in how to measure daily, weekly and monthly active users. Session length earns its keep in two cases: your extension has a genuinely session-shaped job such as a timer, a recorder or a reader, or you are comparing two onboarding flows and need to know whether the second one holds attention longer.

Moderok sends first open, install, update and a once-per-UTC-day ping automatically (automatic events) and counts whatever custom events you name, so the bucketed events above sit next to your active-user counts without extra wiring. The events guide covers naming and property rules, and the product page shows what the dashboard reports.