Skip to content

Install in a Chrome extension

For Chromium browsers: Chrome, Edge, Brave, Opera, Arc. Firefox has its own guide — the SDK is the same, but the manifest and the background lifecycle differ enough that following the wrong page produces a failure that does not explain itself.

1. Install the package

bash
npm install @analyticstrend/extension

Beta versioning

Published at 0.1.0. The API is settled enough to build on, but this is a closed beta and breaking changes will land in minor versions until 1.0.0. Pin an exact version if that matters to you.

2. Initialise in the background service worker

Manifest V3 runs your background code as a service worker that the browser suspends after roughly thirty seconds of inactivity and restarts on demand. Call initBackground at the top level of that file, so it runs on every start.

js
// background.js
import { initBackground } from "@analyticstrend/extension";

const analytics = await initBackground({
  writeKey: "wk_your_key_here",
  uninstallTracking: true,
});

analytics.track("extension_started");

Your write key is on the Settings screen of your dashboard. It is public by design and safe to ship inside your extension: it authorises writing events and nothing else. It cannot read your data.

3. Declare the permissions

json
{
  "manifest_version": 3,
  "background": { "service_worker": "background.js", "type": "module" },
  "host_permissions": ["https://analyticstrend.com/*"]
}

host_permissions is what lets the service worker reach the collector. Without it the requests fail silently, because a blocked fetch looks exactly like an offline device, and the SDK treats both as "retry later".

4. Track from a popup or content script

Only the background context owns the durable queue. A popup or content script sends its event there instead:

js
import { trackFromContentScript } from "@analyticstrend/extension";

trackFromContentScript("popup_opened", { source: "toolbar" });

If the background is not running at that moment the event is dropped rather than queued, because a content script has nowhere durable to keep it. That is the right trade for a page you do not control, but it means content-script events are best-effort where background events are not.

What happens when the service worker is suspended

Nothing is lost. Events are written to chrome.storage.local before any send is attempted, so a teardown mid-flush leaves the queue intact and the next start drains it. Batches the server already accepted are never sent twice.

Verify it

Load the extension unpacked, open it, then look at the Events screen in your dashboard. Events appear in the raw table immediately; the Overview totals update on the hourly rollup, so daily active users will lag by up to an hour on a brand-new project.

Data hosted in Canada. No cookies, no fingerprinting, no personal data.