A Manifest V3 extension has no long-running background page. It has a service worker that Chrome starts for an event and stops again. That one fact shapes a license check: nothing can live in memory between events, and the calls need a short timeout. This page covers the online part, which is activation, validation and deactivation. The signed-token fallback for when the network is down is in offline verification in a Chrome extension. It was not loaded into Chrome.
What Chrome does to your worker
Chrome’s documentation says a service worker is terminated after 30 seconds of inactivity, when a single request takes longer than 5 minutes, or when a fetch() response takes more than 30 seconds to arrive. Events and extension API calls reset the timer, and Chrome tells you to design for unexpected termination. For a license check this means three rules: read state from storage at the start of every handler, use an 8-second timeout on the request so it ends well inside the limit, and never rely on a module-level variable surviving.
manifest.json
{
"manifest_version": 3,
"name": "Inkwell",
"version": "3.2.0",
"background": { "service_worker": "background.js", "type": "module" },
"permissions": ["storage", "alarms"]
}
There is no host_permissions entry. Clavem’s License API sends Access-Control-Allow-Origin: * and answers the preflight with Access-Control-Allow-Headers: content-type, POST and OPTIONS allowed, and a 24-hour cache, so a normal cross-origin fetch from the worker works. A host permission is one more line in the install prompt, so test without it and add it only if your build needs it.
The calls
// background/licensing.js
import { check } from './token.js'; // the offline check, see the offline page
const BASE = 'https://clavem.io';
const PRODUCT_ID = 75; // from your product page
const PUBLIC_KEY = 'kq1…your key…9fA'; // from your product page
async function post(action, body) {
try {
const res = await fetch(`${BASE}/v1/licenses/${action}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(8000),
});
return { status: res.status, body: await res.json().catch(() => ({})), retryAfter: Number(res.headers.get('retry-after')) || null };
} catch {
return null; // offline, DNS failure, timeout
}
}
const load = async () => (await chrome.storage.local.get('license')).license ?? null;
const save = (license) => chrome.storage.local.set({ license });
const clear = () => chrome.storage.local.remove('license');
/** 'licensed' | 'invalid' | 'needs-network' | 'unlicensed'. */
export async function checkLicense(now = Date.now() / 1000) {
const saved = await load();
if (!saved) return 'unlicensed';
const r = await post('validate', { license_key: saved.key, instance_id: saved.instanceId });
if (r?.status === 200 && typeof r.body.valid === 'boolean') {
await save({ ...saved, token: r.body.token ?? saved.token }); // also when not valid: offline, the token then says so
return r.body.valid ? 'licensed' : 'invalid';
}
if (r?.status === 404) { await clear(); return 'invalid'; } // unknown key, or this browser's activation was removed
// No answer, 429 (Retry-After: 60) or 503 (Retry-After: 5): trust the stored token while it is fresh.
return (await check(saved.token, { publicKey: PUBLIC_KEY, productId: PRODUCT_ID, now })) === 'ok' ? 'licensed' : 'needs-network';
}
A known key always answers 200, valid or not, so read valid. A 404 is an unknown key or instance_id not found. A 429 or 503 says nothing about the license, so the worker falls back to the stored token and retries on the next alarm instead of looping.
Wire it to events, not to timers
setTimeout and setInterval do not survive a stopped worker. Use chrome.alarms and the startup events, and create the alarm in both onInstalled and onStartup when it does not exist, because you cannot assume it persists:
// background.js
import { activate, checkLicense } from './background/licensing.js';
async function ensureAlarm() {
if (!(await chrome.alarms.get('license'))) chrome.alarms.create('license', { periodInMinutes: 360 });
}
chrome.runtime.onInstalled.addListener(ensureAlarm);
chrome.runtime.onStartup.addListener(() => { ensureAlarm(); checkLicense(); });
chrome.alarms.onAlarm.addListener((alarm) => { if (alarm.name === 'license') checkLicense(); });
chrome.runtime.onMessage.addListener((message, _sender, reply) => {
if (message.type === 'activate') activate(message.key).then(reply);
if (message.type === 'status') checkLicense().then(reply);
return true; // keeps the message channel open for the async reply
});
Listeners must be registered at the top level of the worker, not inside a promise, or Chrome cannot wake the worker for the event. A popup or an options page sends { type: 'status' } and shows the answer. Content scripts should not call the API themselves. Ask the worker.
Where the state goes
chrome.storage.local stays on this browser profile. chrome.storage.sync does not. Chrome’s documentation says sync data goes to every Chrome browser the user is signed in to, so a saved instance id would reach other computers and let them skip activation while using this seat. chrome.storage.session is in memory, so it is right for a cache and wrong for a key that has to survive a restart. None of the areas is encrypted. Anyone with access to the profile can read the key in DevTools, which is acceptable for a license key and a reason to never store a payment secret there.
There is no hardware id
An extension cannot read a machine id. The fingerprint is therefore an install id: a random UUID created once and kept in chrome.storage.local. Activating again with the same install id returns the same seat. A new profile, a reinstall, or clearing extension data creates a new id and takes another seat, and the old one stays used until the customer removes it. Offer a button that calls deactivate, and tell people the device page at /licenses/manage lists every browser that holds a seat.
What the code returned
before activation: unlicensed
activate TEST-ACTIVE: { state: 'activated' }
online: licensed
server down: licensed
activate TEST-LIMIT: { state: 'limit-reached', used: 3, limit: 3 }
deactivate offline: false, license still saved
deactivate: true, license cleared
Pitfalls specific to extensions
- Return
truefromonMessagewhen you reply asynchronously, or the channel closes before the answer. - Do not keep a flag in a variable. After 30 idle seconds it is gone.
- Do not validate on every popup open. The License API allows 60 requests a minute per key. Read the stored result and refresh on the alarm.
- Updates. An extension published through the Chrome Web Store is updated by the store, so this page has no update check.
Doing this with Clavem
The License API needs no secret, so nothing sensitive ships in the extension. Plan limits never block validation. See the API reference for every field.
Questions
Can a Chrome extension call the License API from the service worker?
Yes. The API answers with Access-Control-Allow-Origin set to a wildcard and allows the preflight request, so fetch works from the service worker. Test it with no host permission, and leave the entry out if it works, which spares customers an extra permission line.
Should I store the license key in chrome.storage.sync?
No. Chrome syncs that area to every browser the user is signed in to, so the saved instance id would appear on other computers and share one seat. Use chrome.storage.local, which stays on this profile.
Why does my license state disappear between events?
Chrome terminates an idle service worker, and its globals are lost. Read the state from chrome.storage at the start of each event handler and write it back, instead of keeping it in module variables.