Use Chrome/WebExtension APIs correctly — storage, tabs, alarms, notifications, contextMenus, identity, and cross-browser compatibility.
chrome.storage, chrome.tabs, chrome.alarms, or other extension APIsThree storage areas for different needs:
// local — persistent, device-specific, 10MB limit
await chrome.storage.local.set({ key: value });
const { key } = await chrome.storage.local.get('key');
// sync — synced across devices (Chrome account), 100KB limit, 8KB per item
await chrome.storage.sync.set({ settings: userSettings });
// session — cleared when browser closes, fast, 10MB, no persistence
await chrome.storage.session.set({ tabState: {} });
// Get current tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// Execute script in tab
await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['inject.js'] });
// Listen for tab updates
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') { /* page loaded */ }
});
// Create repeating alarm (survives service worker termination)
await chrome.alarms.create('sync', { periodInMinutes: 5 });
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'sync') doSync();
});
// Launch OAuth flow (Chrome)
const token = await chrome.identity.getAuthToken({ interactive: true });
// Launch web auth flow (works cross-browser, custom OAuth)
const redirectUrl = chrome.identity.getRedirectURL();
const responseUrl = await chrome.identity.launchWebAuthFlow({
url: `https://provider.com/auth?redirect_uri=${redirectUrl}`,
interactive: true
});
chrome.contextMenus.create({
id: 'myAction',
title: 'Do something with "%s"', // %s = selected text
contexts: ['selection', 'page', 'link', 'image']
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'myAction') { /* handle */ }
});
tabs.executeScriptstorage.session for transient service worker state (not global vars)?storage.sync usage?setInterval in service worker)?chrome.scripting used (not deprecated tabs.executeScript)?runtime.onInstalled listener?storage.sync near quota limit, setInterval in service workerstorage.session for tab-level state, alarms for background schedulingsetInterval / setTimeout in service worker: the worker can terminate before they fire — use chrome.alarmschrome.runtime.onInstalled (re-registered on update), not top-levelstorage.sync has strict limits: 100KB total, 8KB per item, 1800 writes/hour