// One extension API namespace for both browsers. Chrome exposes `chrome.*`; // Firefox exposes the same promise-based API as `browser.*` (and keeps a // callback-based `chrome.*` alias, which we do not use). The bundled // @types/chrome describes the shape, so callers only have to write `ext.` // where they used to write `chrome.`. // // The lookup is lazy rather than a captured value because the unit tests stub // `globalThis.chrome` after modules have been imported, and because a module // that only touches the API inside a function should not fail to load when no // browser is present. type Api = typeof chrome function current(): Api | undefined { const globals = globalThis as typeof globalThis & { browser?: Api chrome?: Api } return globals.browser ?? globals.chrome } export const ext: Api = new Proxy({} as Api, { get(_target, key) { return current()?.[key as keyof Api] }, }) /** * Whether this is Firefox. The presence of `browser` is not the test: Chrome * 148 also exposes a promise-based `browser` alias, so a Chrome service worker * would otherwise take the Firefox redirect URI and fail the token exchange. * `runtime.getBrowserInfo` is Firefox-only, and the user agent is the fallback * for a context that lacks it. */ function detectFirefox(): boolean { const runtime = current()?.runtime as | (typeof chrome.runtime & { getBrowserInfo?: unknown }) | undefined if (typeof runtime?.getBrowserInfo === 'function') return true return typeof navigator !== 'undefined' && /\bFirefox\//.test(navigator.userAgent) } export const isFirefox = detectFirefox() /** Chrome MV3 has `chrome.offscreen`; Firefox MV3 has no equivalent. */ export function hasOffscreenSupport(): boolean { return typeof ext.offscreen?.createDocument === 'function' }