# Extension.js > Build browser extensions for Chrome, Edge, Firefox, and Safari with one modern workflow. Extension.js handles manifest compilation, browser-specific output, reload behavior, and packaging so you can focus on product features. > ## Agent Instructions > Extension.js needs Node.js 22.12 or newer; Node.js 18 and 20 do not work. It also runs on Deno 2.5+ and Bun 1.2+. > The default browser target is chromium and a build lands in dist/, so dist/chromium by default. extension build writes a zip only when --zip is passed. > Prefix a manifest key with a browser name when browsers differ. chromium: covers every Chromium-family target and Safari builds read it too. Since 4.1.19 chrome: means Chrome alone and edge: means Edge alone. > Write one background.service_worker in manifest.json instead of hand-writing per-browser background keys; Extension.js converts it for each browser. > package.json or deno.json marks the project root, not manifest.json. A config file is optional, and only extension.config.js, .mjs and .cjs are loaded, never .ts. > The bundler is Rspack, extended through the config hook in extension.config.js. A project needs no separate bundler config file. > Use --no-browser to skip the browser launch; --no-runner no longer exists and --no-open still launches the browser. Use --output for machine output; --format and --wait-format are deprecated. # Browser launch flags for Chrome, Firefox, and Edge Source: https://extension.js.org/docs/browsers/browser-flags Use firefox://flags, chrome://flags, and browser launch flags in Extension.js. Control Chrome, Firefox, and Edge runtime behavior during extension development. Control browser launch behavior for debugging, automation, and runtime experiments. > [!NOTE] > > **Looking for `chrome://flags` or `edge://flags`?** Type it into your address > bar, which is the browser's built-in page. **Firefox has no `firefox://flags`**; > use `about:config` instead. > > If you're toggling flags to **test or build a browser extension**, Extension.js > applies them per-project automatically across Chrome, Edge, and Firefox, so you > don't pass flags by hand on every run. [Create your first extension in 30 > seconds →](/docs/getting-started) Extension.js is a framework that builds and runs browser extensions from one `manifest.json` for Chrome, Edge, Firefox, and Safari. To create an extension, run these commands in a terminal: ```bash theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} npx extension@latest create my-extension cd my-extension npm install npm run dev ``` This page is part of the Extension.js documentation. `npx extension@latest dev` launches the browser with the flags on this page applied. Tune browser launch behavior without changing extension source code. Extension.js merges browser flags from your `extension.config.*` and applies them in `dev`, `preview`, and `start` flows. ## Does Firefox have `firefox://flags`? Firefox does not use `firefox://flags` the way Chromium browsers use `chrome://flags` or `edge://flags`. Firefox exposes runtime toggles through `about:config` (preferences) and accepts launch flags from the command line. If you searched for `firefox://flags`, `firefox //flags`, `browser://flags`, `mozilla://flags`, or `about flags firefox`, you are probably trying to change browser behavior during extension development. In Extension.js, do that in two places: * Use [`browserFlags`](/docs/browsers/browser-flags) for launch-time flags Extension.js passes to the browser binary. * Use [Firefox preferences](/docs/browsers/browser-preferences) for repeatable Gecko runtime behavior that would otherwise live in `about:config`. Both work for Chrome, Edge, and Firefox extension development from the same Extension.js project. ## Flags in other browsers Extension.js launches and configures any Chromium-based browser the same way. * **`brave://flags`, `opera://flags`, `vivaldi://flags`, `yandex://flags`**: all Chromium-based, so they behave identically to `chrome://flags`, and Extension.js manages them per-project. * **`internet://flags` and `browser://flags`**: these are not real browser schemes. You are most likely looking for `chrome://flags` (Chromium) or `about:config` (Firefox). * **`edge://flags`**: Edge is Chromium, so it works exactly like Chrome in Extension.js. Building an extension that needs specific flags at launch? Set them once in `extension.config.*` and Extension.js applies them every run. See [`browserFlags`](/docs/browsers/browser-flags) below. ## GPU and WebGL flags A headless session, a container, or a virtual machine often has no GPU. WebGL contexts then fail to create, and canvas code that needs one throws. Pass the Chromium switches through `browserFlags`: ```js theme={null} export default { browser: { chrome: { browserFlags: [ "--ignore-gpu-blocklist", "--use-gl=angle", "--use-angle=swiftshader", ], }, }, }; ``` `--ignore-gpu-blocklist` lets Chromium use a GPU that its blocklist would refuse. `--use-gl=angle` with `--use-angle=swiftshader` renders WebGL in software, which is the right choice in continuous integration. `--enable-unsafe-webgpu` turns on WebGPU where the browser still gates it. Firefox has no equivalent switches. Set `webgl.force-enabled` through browser preferences instead. ## Template examples ### `new-browser-flags` ![new-browser-flags template screenshot](https://mintcdn.com/extensionjs/etcqPhDg4wwyPkcC/images/examples/newtab-browser-flags/screenshot.png?fit=max\&auto=format\&n=etcqPhDg4wwyPkcC\&q=85\&s=21d85e952a28669ccc089b6efa0e48c4) See browser flags in action with a new-tab extension that configures launch behavior. ```bash npm theme={null} npx extension@latest create my-extension --template=newtab-browser-flags ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=newtab-browser-flags ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=newtab-browser-flags ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=newtab-browser-flags ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=newtab-browser-flags ``` Repository: [extension-js/templates/newtab-browser-flags](https://github.com/extension-js/templates/tree/main/examples/newtab-browser-flags) ## How it works Configure flags in `extension.config.*`: * `browser..browserFlags` * `commands.dev|start|preview.browserFlags` * Optional `excludeBrowserFlags` to remove defaults or user flags (behavior depends on whether you target Chromium or Firefox). Override order: browser defaults → command defaults → CLI-selected command context. ## Flag capabilities | Config key | What it does | | - | - | | `browser..browserFlags` | Sets default launch flags for a specific browser target. | | `commands.dev.browserFlags` | Adds or overrides flags for `dev` runs. | | `commands.start.browserFlags` | Adds or overrides flags for `start` runs. | | `commands.preview.browserFlags` | Adds or overrides flags for `preview` runs. | | `browser..excludeBrowserFlags` | Removes matching default or user flags for a target. | | `commands..excludeBrowserFlags` | Removes flags in a command-specific context. | [Extension.js: browser flags](https://www.youtube-nocookie.com/embed/LwZrJu80bUI?rel=0) ### Example configuration ```js theme={null} export default { browser: { chrome: { browserFlags: ["--disable-web-security", "--auto-open-devtools-for-tabs"], excludeBrowserFlags: ["--mute-audio"], }, firefox: { browserFlags: ["--devtools", "--new-instance"], excludeBrowserFlags: ["--devtools"], }, }, }; ``` ## Chromium vs Firefox behavior * **Chromium family (`chrome`, `edge`, `chromium`, `chromium-based`)** * Starts from an internal default flag set, then appends your `browserFlags`. * `excludeBrowserFlags` removes matching default and user flags. * Extension.js manages `--load-extension=...` and filters it out from user-provided flags. * **Firefox/Gecko family (`firefox`, `gecko-based` / `firefox-based`)** * Uses user-provided `browserFlags` (no large default flag bundle like Chromium). * `excludeBrowserFlags` removes matching user flags, with the same rule as Chromium. Both families share one exclusion rule: a flag is removed when it equals the exclude value, or when the exclude value names a switch whose value continues with `=` or `,`. So `--disable-features` also removes `--disable-features=Translate`, while `--dev` never removes `--devtools`. ### Default Chromium flags Extension.js applies these flags automatically when launching Chromium-family browsers. Use `excludeBrowserFlags` to remove any you do not need. | Flag | Purpose | | - | - | | `--no-first-run` | Disable first run experience | | `--disable-client-side-phishing-detection` | Disable phishing detection | | `--disable-sync` | Disable sync to avoid account prompts | | `--disable-component-extensions-with-background-pages` | Disable built-in extensions not affected by `--disable-extensions` | | `--disable-default-apps` | Disable installation of default apps | | `--disable-features=InterestFeedContentSuggestions` | Disable Discover feed on new tab page (NTP) | | `--disable-features=Translate` | Disable Chrome translation | | `--hide-scrollbars` | Hide scrollbars from screenshots | | `--mute-audio` | Mute any audio | | `--no-default-browser-check` | Disable default browser check prompt | | `--ash-no-nudges` | Avoid user education nudges | | `--disable-search-engine-choice-screen` | Disable search engine choice screen | | `--disable-features=MediaRoute` | Disable Chrome Media Router background networking | | `--use-mock-keychain` | Use mock keychain on Mac to prevent blocking dialogs | | `--disable-background-networking` | Disable background network services | | `--disable-breakpad` | Disable crashdump collection | | `--disable-component-update` | Disable component updates | | `--disable-domain-reliability` | Disable domain reliability monitoring | | `--no-pings` | Disable hyperlink auditing pings | | `--enable-features=SidePanelUpdates` | Ensure side panel is visible | | `--disable-features=DisableLoadExtensionCommandLineSwitch` | Allow `--load-extension` at the command line | | `--disable-features=ExtensionDisableUnsupportedDeveloper` | Keep unpacked extensions alive across `runtime.reload()` (Chromium 152+) | | `--enable-unsafe-extension-debugging` | Allow Chrome DevTools Protocol (CDP) extension management (Chrome 126+) | | `--silent-debugger-extension-api` | Suppress the "X is debugging this browser" infobar | ### The `debugger` permission changes two flags An extension that attaches `chrome.debugger` must handle the Cancel button on Chrome's debugging bar. From the release after 4.1.39, a session shows that bar when your manifest lists `debugger` under `permissions` or `optional_permissions`: * `--silent-debugger-extension-api` is left out, because that flag hides the bar. * `--disable-infobars` is passed, because it clears the notice that holds the bar back. Chrome for Testing shows its own testing notice in the same slot, and the debugging bar waits behind it. `--disable-infobars` hides every infobar that has no button, so the bar can show. Other Chromium builds honor that flag only in headless mode. To hide the bar again, list `--silent-debugger-extension-api` under `browserFlags`. To keep the testing notice, list `--disable-infobars` under `excludeBrowserFlags`. The identity card prints a `Dev flag` line for each verdict: ```text theme={null} Dev flag --silent-debugger-extension-api left out for the debugger permission, browserFlags restores it Dev flag --disable-infobars passed for the debugger permission, clears the testing notice so the debugger bar shows ``` `ready.json` carries the reason for each verdict under [`devAdditions`](/docs/contracts/ready-json#dev-additions). ### Always-on session flags Beyond the default table, every Chromium launch gets a fixed block of session-stability flags. They keep background timers, occluded windows, and renderer throttling from distorting automated and AI-driven sessions. `excludeBrowserFlags` cannot remove them: ```text theme={null} --disable-background-timer-throttling --disable-renderer-backgrounding --disable-backgrounding-occluded-windows --disable-features=TranslateUI --disable-hang-monitor --disable-prompt-on-repost --memory-pressure-off --max_old_space_size=4096 --disable-dev-shm-usage ``` In `dev` mode only, Extension.js also wires the debugging channel with three flags: `--remote-debugging-port=`, `--remote-debugging-address=127.0.0.1`, and `--remote-debugging-pipe`. Production-mode launches (`start`, `preview`) skip this trio. ### Feature-switch merging Chromium honors only the last occurrence of a repeated switch. Extension.js therefore merges every `--enable-features` and `--disable-features` occurrence into one comma-joined switch each. Defaults, config, and environment values all merge, and duplicate feature names are removed. You can safely pass `--disable-features=Foo` in `browserFlags` without erasing the defaults. ### Environment switches * `EXTENSION_BROWSER_FLAGS` appends whitespace-separated flags to every launch. It is applied after config flags and after `excludeBrowserFlags` filtering, so `excludeBrowserFlags` cannot remove flags that come from this variable. * `EXTENSION_HEADLESS=1` (or `true`) forces `--headless=new`, unless a `--headless` flavor was already passed through config or environment flags. Use it as a focus-steal guard for automated sessions. > [!NOTE] > > In Docker, continuous integration (CI), or containerized environments, > Extension.js also applies `--no-sandbox` and `--disable-setuid-sandbox` > automatically. On Linux it detects a container through any of these signals: > `CI=true`, a `/.dockerenv` file, a `/run/.containerenv` file, > `REMOTE_CONTAINERS=true`, `CODESPACES=true`, or a set `container` variable. ## Supported targets and references | Browser | Usage | More information | | - | - | - | | Chrome | `extension dev --browser=chrome` | [Chrome Flags](https://peter.sh/experiments/chromium-command-line-switches/) | | Edge | `extension dev --browser=edge` | [Edge Flags](https://docs.microsoft.com/en-us/deployedge/microsoft-edge-policies) | | Firefox | `extension dev --browser=firefox` | [Firefox Flags](https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options) | | Chromium-based | `extension dev --browser=chromium-based` | [Chromium Flags](https://peter.sh/experiments/chromium-command-line-switches/) | | Gecko-based | `extension dev --browser=gecko-based` | Firefox-based browsers share the same flags as Firefox. | Use binary flags when needed for engine-based targets: * `--chromium-binary=...` * `--gecko-binary=...` ## Best practices * **Add only necessary flags**: Minimize long flag lists to reduce flaky or non-portable setups. * **Prefer `excludeBrowserFlags` over replacing defaults**: Remove only what conflicts with your workflow. * **Do not pass `--load-extension` manually**: Extension.js manages extension loading flags internally. * **Validate per browser family**: A flag working in Chromium may be invalid or ignored in Firefox. ## Next steps * Learn more about [Browser preferences](/docs/browsers/browser-preferences). * Learn more about [Browser profile](/docs/browsers/browser-profile). * Choose a target in [Browsers available](/docs/browsers/browsers-available). * Wire flags through [`extension.config.*`](/docs/features/extension-configuration). * New to extension tooling? Start with a [browser extension framework](/docs/compare) overview. # Firefox and Gecko runtime preferences setup Source: https://extension.js.org/docs/browsers/browser-preferences Set Firefox and Gecko runtime preferences for development without editing extension source. Configure homepage, devtools, and notification defaults. Get repeatable browser behavior during development (for example, homepage defaults, devtools settings, or notification behavior) without editing extension code. Extension.js reads `preferences` from `extension.config.*` and applies them at browser launch. Firefox and Gecko targets get a `user.js` file. Chromium targets get a seeded `Default/Preferences` file. ## How it works Configure preferences in `extension.config.js` (or `.mjs` / `.cjs`) under: * `browser..preferences` * `commands.dev|start|preview.preferences` Command-level values can override browser defaults. ## Preference capabilities | Preference key | What it does | | - | - | | `browser..preferences` | Sets default preferences for a specific browser target. | | `commands.dev.preferences` | Sets or overrides preferences for `dev` runs. | | `commands.start.preferences` | Sets or overrides preferences for `start` runs. | | `commands.preview.preferences` | Sets or overrides preferences for `preview` runs. | ## Firefox and Gecko-based behavior ### Example configuration ```js theme={null} export default { browser: { firefox: { preferences: { "browser.startup.homepage": "https://developer.mozilla.org", "devtools.theme": "dark", "dom.webnotifications.enabled": false, }, }, }, }; ``` In Firefox/Gecko flows, Extension.js writes a `user.js` file into the active profile (managed or explicit profile) and merges: * Internal baseline preferences required for development and runtime behavior. * Your custom `preferences` values (your values win on key conflicts). If you enable system profile mode (`EXTENSION_USE_SYSTEM_PROFILE=true`), Extension.js does not write a managed profile file. ## Chromium-family behavior Chromium-family launches (`chrome`, `edge`, `chromium`, `chromium-based`) seed your `preferences` too, through the profile rather than a `user.js` file. At launch, Extension.js deep-merges your `preferences` object into the vendor's master-preferences baseline. The result is written once to `Default/Preferences` inside the active profile. The write happens only when that file does not exist yet, so a fresh profile gets seeded and an existing profile keeps its state. Chrome and Edge each have their own baseline object, chosen by the target you run. ```js theme={null} export default { browser: { chrome: { preferences: { download: { prompt_for_download: false }, }, }, }, }; ``` Your values win over the baseline on key conflicts, and nested objects merge key by key. > [!NOTE] > > Because the write is once per profile, a persisted profile (`persistProfile` > or `keepProfileChanges`) does not pick up later preference edits. Delete the > profile, or run an ephemeral profile, to re-seed. ### The startup preference on a kept profile A profile that outlives the session, such as `--profile `, remembers its open pages. On its next launch, Chrome would restore the pages of the previous run, ahead of your extension. From the release after 4.1.39, `dev` sets `session.restore_on_startup` to `5` in such a profile, so the browser opens a new tab. The session writes the value once through the browser, and it stays in that profile afterward. The identity card says so: ```text theme={null} Dev pref session.restore_on_startup=5 written to this kept profile and stays there, preferences changes it ``` To keep the browser restoring its last session, set the preference yourself before the first launch: ```js theme={null} export default { browser: { chrome: { preferences: { session: { restore_on_startup: 1 }, }, }, }, }; ``` The card then reads `left to the browser, preferences sets it`. A profile that already has the value keeps it until you change "On startup" in `chrome://settings`. An ephemeral profile is deleted on exit, so the session writes nothing there. For launch behavior that Chromium controls through the command line, use flags instead: * `browserFlags` * `excludeBrowserFlags` * `profile` / `persistProfile` For CI or harnesses that must add launch flags without touching `extension.config.js`, set `EXTENSION_BROWSER_FLAGS` (whitespace-separated, for example `--headless=new`). It applies to every launched browser and is appended after config `browserFlags`, so the environment wins when a flag repeats. ## Dark mode defaults Extension.js injects dark-mode defaults unless you already define those keys: * Chromium family: dark-mode launch flags * Firefox/Gecko family: dark-mode preference keys (for UI + content color scheme) Your explicit `preferences`/flags override these defaults. ## Interface example ```js theme={null} export default { commands: { dev: { browser: "firefox", preferences: { "devtools.theme": "dark", }, }, }, }; ``` ### Example with custom profile ```js theme={null} export default { browser: { firefox: { profile: "path/to/custom-profile", preferences: { "browser.startup.homepage": "https://example.com", }, }, }, }; ``` ## More detailed preference references For a comprehensive list of available Firefox preferences, explore the [Firefox source code](https://searchfox.org/mozilla-central/source/). Mozilla defines many defaults in `all.js` or `firefox.js`. ## Best practices * **Prefer browser-scoped preferences**: Keep Firefox/Gecko preference keys under browser-targeted configuration blocks. * **Use command overrides for temporary experiments**: Put short-lived preference tweaks in `commands.dev`. * **Keep profiles isolated**: Use separate profiles for reproducible debugging. * **Use flags for Chromium launch tuning**: Preferences seed the profile once, so per-run behavior changes belong in flags. ## Next steps * Learn more about [Browser flags](/docs/browsers/browser-flags). * Learn more about [Browser profile](/docs/browsers/browser-profile). # Browser profiles for isolated dev runs Source: https://extension.js.org/docs/browsers/browser-profile Manage browser state isolation during extension development with managed, persistent, or custom profile paths for Chrome and Firefox. Control browser state isolation during development with managed, persistent, or custom profiles. Keep browser sessions isolated or persistent based on your workflow. Extension.js launches browsers with profile-aware defaults. Choose clean runs, reusable state, or an explicit local profile path. ## How it works Extension.js chooses the profile mode in this order: 1. System profile mode when `profile: false` or `EXTENSION_USE_SYSTEM_PROFILE=true` 2. Explicit `profile` path (if provided) 3. Managed profile mode (default) * temporary (ephemeral) by default * persistent when `persistProfile: true` or `keepProfileChanges: true` ### How `--profile` values are read The CLI delivers flag values as strings, so Extension.js normalizes them: * `--profile=false` (or `profile: false` in config) means the browser's own default profile. * `--profile=true` means the managed default, the same as leaving the option unset. * Any other string is an explicit profile path. A relative `--profile` path resolves against the project (compilation context), not your shell's working directory. This keeps sequential runs of different projects from collapsing onto one shared profile. ### System profile mode on Firefox and other Gecko browsers > [!WARNING] > > Extension.js refuses to launch Firefox or any other Gecko-based browser in > system profile mode. Use it with Chromium-family browsers only. Extension.js installs the add-on in a Gecko browser over remote debugging, and a browser's own profile keeps remote debugging off. So with `--profile=false`, `profile: false`, or `EXTENSION_USE_SYSTEM_PROFILE=true`, `dev`, `start`, and `preview` stop before the browser launches. Nothing opens on your everyday profile. This applies to every Gecko target the CLI launches: `firefox`, `waterfox`, `librewolf`, `zen`, `floorp`, and `gecko-based`. All three commands print a block that names the source of the setting and the two ways out. The browser name follows your target, and the `SET BY` line names every source that is active (`--profile=false`, `profile: false in extension.config.js`, or `EXTENSION_USE_SYSTEM_PROFILE=true`): ```text theme={null} Firefox can't load the add-on in its own profile, so it was not launched. SET BY --profile=false Remote debugging is off in a browser's own profile, and the add-on can only be installed over it. To fix, drop --profile=false, then let Extension.js manage the profile or pass --profile= to use a profile of your own. ``` `extension dev` keeps the dev server running and watching, with `ready.json` in `error` (code `browser_launch_failed`, `browserLaunchFailedCode: "E_FLAG_NOT_SUPPORTED_HERE"`). `extension start` and `extension preview` exit with code 1. With `--output json`, every command fails with `E_FLAG_NOT_SUPPORTED_HERE` and `status: "usage"`. Earlier versions launched the browser on your own profile with nothing loaded in it. To get a working session, take one of the two ways out the block names: * Drop `--profile=false` (and `profile: false` or `EXTENSION_USE_SYSTEM_PROFILE`) so Extension.js manages the profile and installs the add-on. Add `persistProfile: true` to keep logins and state between runs, or seed the managed profile from an existing one with [`copyFromProfile`](#seeding-with-copyfromprofile). * Pass `--profile=` to launch with a profile directory of your own. Extension.js installs the add-on into it. ## Profile capabilities | Config / option | What it does | | - | - | | `browser..profile` | Uses an explicit profile folder for that browser target. | | `commands.dev.profile` | Uses an explicit profile only for `dev`. | | `commands.start.profile` | Uses an explicit profile only for `start`. | | `commands.preview.profile` | Uses an explicit profile only for `preview`. | | `browser..persistProfile` | Reuses managed profile state between runs for a target. | | `commands..persistProfile` | Reuses managed profile state in a command-specific context. | | `keepProfileChanges` | Keeps the managed profile and its changes across runs (same effect as `persistProfile`). | | `copyFromProfile` | Seeds the managed profile as a copy of an existing profile directory. | | `--profile=/abs/path` | CLI override for explicit profile path. | | `--profile=false` | Launches the browser's own default profile (system mode). Chromium family only, see above. | | `EXTENSION_USE_SYSTEM_PROFILE=true` | Uses the OS/browser system profile instead of managed profiles. | | `EXTJS_USE_SYSTEM_PROFILE=true` | Alias of `EXTENSION_USE_SYSTEM_PROFILE`. | ### Seeding with `copyFromProfile` `copyFromProfile` copies the source directory into the managed profile before launch. The copy happens only when the target is fresh, meaning it does not exist or is empty. A persisted profile therefore seeds once, and your later changes survive every run. ## Profile modes | Mode | How to enable | Typical use | | - | - | - | | Managed ephemeral | default | clean runs with isolated state | | Managed persistent | `persistProfile: true` or `keepProfileChanges: true` | iterative debugging with stable browser state | | Explicit custom profile | `profile: "/abs/path"` or `--profile=/abs/path` | reuse an existing profile | | System profile | `--profile=false` or `EXTENSION_USE_SYSTEM_PROFILE=true` | launch with OS/browser default profile (Chromium family only) | Extension.js creates managed profiles under: * `dist/extension-js/profiles/-profile/<...>` Persistent mode uses: * `dist/extension-js/profiles/-profile/dev` Each ephemeral run gets a generated three-word leaf name in adjective-color-animal form, for example `brave-magenta-heron`. The name is random per run, so do not hardcode it. Read the `profilePath` field in the session's `ready.json` to find the profile a run is using. [Extension.js: persistent browser profile](https://www.youtube-nocookie.com/embed/w5zkMas9Ef4?rel=0) ## Configure in `extension.config.*` ```js theme={null} export default { browser: { chrome: { // Use your own profile folder: profile: "path/to/custom/profile", }, firefox: { // Keep a stable managed profile for repeated sessions: persistProfile: true, }, edge: { // Keep changes across runs and seed once from an existing profile: keepProfileChanges: true, copyFromProfile: "/path/to/existing/profile", }, }, }; ``` You can also scope profile defaults by command: ```js theme={null} export default { commands: { dev: { persistProfile: true, }, }, }; ``` ## CLI usage Use an explicit profile path directly: ```bash theme={null} npx extension@latest dev --browser=chrome --profile=/path/to/custom/profile ``` Works similarly with `start` and `preview`. ## Lifecycle notes * Extension.js creates ephemeral managed profiles for each run. * Extension.js reuses the persistent managed profile (`dev`) across runs. * Each ephemeral profile carries a `.extension-js-managed-profile` marker file. On browser exit, Extension.js removes only directories that carry the marker, so kept and explicit profiles are never reclaimed. * Extension.js also sweeps stale marked profiles on the next launch. Set `EXTENSION_TMP_PROFILE_MAX_AGE_HOURS` to control the maximum age (default 12 hours). * On every Firefox launch, Extension.js deletes the profile's `startupCache` directory. A pinned or persisted profile can otherwise serve stale extension code across a full dev restart. ## Locked Chromium profiles > [!WARNING] > > If another live browser process on the same machine owns the profile, > Extension.js refuses to launch instead of corrupting it. Close that browser or > choose a different profile first. Before a Chromium launch, Extension.js reads the profile's `SingletonLock` artifact. A lock that names a dead process or another host is stale. Extension.js removes the stale `SingletonLock`, `SingletonSocket`, and `SingletonCookie` files and launches normally. When the owning process is still alive on this host, the launch aborts instead. The session's `ready.json` is stamped with the `profile_locked` error code, so machine consumers never parse the error sentence. ## Privacy A managed profile is a full browser profile. It holds cookies, history, and login data from anything you do in that browser session. Extension.js writes a `.gitignore` with a `*` rule into `dist/extension-js` once, so profiles and session state never reach git. Do not commit or ship this directory. ## Best practices * **Use managed ephemeral profiles for baseline testing**: Reduces hidden state and flaky reproductions. * **Use `persistProfile` for long-lived debug sessions**: Keep auth/session/devtools state between runs. * **Keep custom profiles per browser family**: Avoid cross-browser contamination. * **Use system profile mode intentionally**: Useful for reproduction on Chromium-family browsers, but less isolated than managed profiles. Extension.js refuses to launch a Gecko browser in this mode. ## Next steps * Learn more about [Browser preferences](/docs/browsers/browser-preferences). * Learn more about [Browser flags](/docs/browsers/browser-flags). # Browsers supported by Extension.js Source: https://extension.js.org/docs/browsers/browsers-available See which browsers Extension.js supports. Run and test extensions across Chrome, Edge, Firefox, and custom binaries from a single CLI workflow. See which browsers Extension.js supports and validate your extension across Chrome, Edge, Firefox, and custom binaries from a single CLI workflow within the same project. ## Choose the right target | Target | Use when | Example | | - | - | - | | `chromium` | Fast default local development | `extension dev --browser=chromium` | | `chrome` | Validating Chrome-specific behavior | `extension dev --browser=chrome` | | `edge` | Validating Edge distribution behavior | `extension dev --browser=edge` | | `firefox` | Validating Gecko compatibility and APIs | `extension dev --browser=firefox` | | `chrome,firefox` | Release checks across both major engines | `extension build --browser=chrome,firefox` | | Named forks | Running an installed fork by name (auto-located) | `extension dev --browser=brave` (also `opera`, `vivaldi`, `yandex`, `waterfox`, `librewolf`, `zen`, `floorp`) | | `chromium-based` | Custom Chromium binaries in `dev`; family-generic `build` artifacts | `extension dev --browser=chromium-based --chromium-binary=/path/to/browser` | | `gecko-based` | Custom Firefox-family binaries in `dev`; family-generic `build` artifacts | `extension dev --browser=gecko-based --gecko-binary=/path/to/browser` | | `safari` | Developing or building a Safari app on macOS (Xcode required) | `extension dev --browser=safari` | | `chromium-emulator` | A dev session in an emulated Chromium that runs in a web page | `extension dev --browser=chromium-emulator` | ## How it works Use `--browser` to choose a target in `dev`, `start`, `preview`, and `build`. If you do not specify a browser, the CLI defaults to `chromium`. `--browser` accepts exactly these values, alone or comma-separated: ```text theme={null} chrome | chromium | edge | firefox | brave | opera | vivaldi | yandex | waterfox | librewolf | zen | floorp | chromium-based | gecko-based | firefox-based | safari | webkit-based | chromium-emulator ``` `--browser=all` is also accepted and expands to `chrome, edge, firefox`. > [!WARNING] > > Prefer `chromium` (or Chrome for Testing via `npx extension install chrome`) > over branded Chrome for development. Recent branded Chrome builds (150+) drop > the `--load-extension` switch unless a policy disables that behavior. A > dropped switch looks exactly like a healthy launch. When Extension.js cannot > confirm the load, it warns and points you at `chrome://extensions`. `safari` (and its `webkit-based` alias) is the exception: it is a **macOS-only** target supported by `build` and `dev`, not by `preview` or `start`. A Safari dev session streams logs and reloads on save. See [Building Safari extensions](/docs/browsers/safari). `chromium-emulator` (from 4.1.38) is a dev target too: `dev` opens an emulated Chromium that runs your extension inside a web page, and `build` writes `dist/chromium-emulator`. `start` and `preview` refuse it with `E_UNSUPPORTED_BROWSER`, because the page reads your build from the dev server. See [Emulated Chromium](/docs/commands/dev#emulated-chromium). [Extension.js: Chromium, Edge and Firefox from one dev command](https://www.youtube-nocookie.com/embed/YBOIpiB_SHQ?rel=0) ## Requested target vs. launch binary The browser you request determines the artifact. The binary is just the runtime. When you run `extension dev --browser=chromium`, Extension.js always: * Writes output to `dist/chromium` (the folder is named after the requested target, never after the binary that launches). * Resolves [browser-specific manifest fields](/docs/features/browser-specific-fields) for the requested target. If the requested browser is not installed, Extension.js does not change the target. For `chrome` and `chromium` it looks for another managed Chromium-family binary (one previously downloaded by `npx extension install`) and uses it as the runtime instead: * Requested `chromium` missing: falls back to managed Chrome, then managed Edge. * Requested `chrome` missing: falls back to managed Chromium, then managed Edge. When this happens, the CLI prints a warn naming the missing browser and the fix, for example `npx extension install chromium`. The warn deliberately omits the substitute binary path. Read that path from `binary` in [`ready.json`](/docs/contracts/ready-json). The output folder and the emitted manifest are exactly what they would be without the fallback. ### What `--browser=edge` runs `edge` never swaps to another browser, and it has no pinned managed copy. `npx extension install edge` installs Microsoft Edge on your system through Playwright. Extension.js resolves the Edge binary in this order: 1. The path in `--chromium-binary`, when passed. 2. The path in the `EDGE_BINARY` environment variable, when set. 3. The Edge that is installed on your system. The identity card then reads `Edge (system install)`. When nothing resolves, the command prints install guidance (`npx extension install edge`) and exits with code `1`. There is no silent Chromium substitute for a missing Edge. If a Chromium window still surprises you, read `binary` in `ready.json`. It names the exact binary that launched, and `binaryProvenance` tells you why. A requested `chrome` or `chromium` can borrow a managed family binary (see above), but a requested `edge` cannot. The output contract holds either way: `dist/edge` exists only when `edge` was the requested target. ### How the binary is chosen From the release after 4.1.39, `dev`, `start`, and `preview` resolve the binary in one order for every browser: 1. The flag, `--chromium-binary` or `--gecko-binary`. 2. The environment variable of the browser. 3. The managed binary from `npx extension install `. 4. The system install. | Browser | Variables, in the order that they are read | | - | - | | `chrome` | `CHROME_FOR_TESTING_PATH`, `CHROMIUM_BINARY`, `CHROME_BINARY` | | `chromium` | `CHROMIUM_BINARY` | | `edge` | `EDGE_BINARY` | | `firefox` | `FIREFOX_BINARY` | A variable is a choice, as the flag is. A variable that names a missing path, or a file that cannot run, fails the launch with `E_BROWSER_BINARY_INVALID`. The run never skips it for the next step. Requested `chrome` still refuses a branded system Chrome. A variable that names branded Chrome is not taken, and the run continues with the managed binary. For Firefox, the managed step prefers a stable build. A nightly that sits in the same cache runs only when no stable build is there, and the card then says `Firefox Nightly`. ### Binary provenance labels `ready.json` records where the session's binary came from in `binaryProvenance`: | Label | Meaning | | - | - | | `managed` | A binary from the managed cache (`npx extension install `). | | `pinned` | A binary that a flag or a binary variable named. `binaryPinnedBy` says which one. | | `system` | A browser found on your system. | | `snapshot` | The managed Chromium tip-of-tree snapshot. | The identity card has no Binary row. Its Browser row carries a note for the two cases that you can act on: ```text theme={null} Browser Firefox 144.0 (pinned with FIREFOX_BINARY) Browser Edge 142.0.3595.53 (system install) ``` `(pinned with )` names what chose the binary. `(system install)` prints for `chrome`, `chromium`, `edge`, and `firefox` when the binary came from your system. A managed binary and a named fork get no note. ### Chromium snapshots vs stable The managed `chromium` install is a tip-of-tree snapshot, not a stable release. When a stable system Chromium exists, Extension.js swaps to it automatically and prints a warn with the opt-out. Set `EXTENSION_PREFER_CHROMIUM_SNAPSHOT=true` to keep the cached snapshot instead. Within the Chromium family this substitution is safe: `dist/chrome` and `dist/chromium` are byte-identical because manifest prefixes resolve per engine family, not per vendor. See [Browser-specific manifest fields](/docs/features/browser-specific-fields) for the prefix rules. To pre-install managed binaries for reproducible runs, use `npx extension install ` or `npx extension install all` (which covers `chromium` too). ## Supported browsers Named browser targets: | Browser | Usage | | - | - | | **Chrome** | `npx extension dev --browser=chrome` | | **Edge** | `npx extension dev --browser=edge` | | **Firefox** | `npx extension dev --browser=firefox` | | **Chromium** | `npx extension dev --browser=chromium` | Named forks (auto-located from your system, no binary path required): | Browser | Engine | Usage | | - | - | - | | **Brave** | Chromium | `npx extension dev --browser=brave` | | **Opera** | Chromium | `npx extension dev --browser=opera` | | **Vivaldi** | Chromium | `npx extension dev --browser=vivaldi` | | **Yandex** | Chromium | `npx extension dev --browser=yandex` | | **Waterfox** | Gecko | `npx extension dev --browser=waterfox` | | **LibreWolf** | Gecko | `npx extension dev --browser=librewolf` | | **Zen** | Gecko | `npx extension dev --browser=zen` | | **Floorp** | Gecko | `npx extension dev --browser=floorp` | If a named fork is not installed, Extension.js exits with install guidance. See [Running other browsers](/docs/browsers/running-other-browsers). Engine-based targets (custom binary required): | Engine target | Usage | | - | - | | **Chromium-based** | `npx extension dev --browser=chromium-based --chromium-binary=/path/to/browser` | | **Gecko-based** (`firefox-based`) | `npx extension dev --browser=gecko-based --gecko-binary=/path/to/browser` | Extension.js treats `firefox-based` as a Gecko engine target internally. Mobile browsers such as Samsung Internet, Chrome for Android, and Firefox for Android are not launch targets. Build the Firefox output and follow that browser's own sideloading flow. ### What engine targets are for `chromium-based` and `gecko-based` target an engine family instead of one vendor. In `dev`, `start`, and `preview`, they run a binary that has no named target. Think a nightly fork, an in-house build, or a fork that the built-in locators do not know. In `build`, they exist for distribution, and no binary is involved at all: * `extension build --browser=chromium-based` writes a family-generic artifact to `dist/chromium-based`. * That artifact resolves `chromium:` manifest prefixes, reads `.env.chromium-based`, and sets `EXTENSION_BROWSER=chromium-based`. * Ship that one package to users on Chrome, Brave, Edge, or any other Chromium fork. Choose a named target (`chrome`, `edge`) when a store build needs vendor-specific manifest fields. Choose an engine target when one artifact should serve the whole family. See [What engine targets mean for `build`](/docs/commands/build#what-engine-targets-mean-for-build). ## Safari and other WebKit targets In addition to the Chromium family and Firefox (Gecko engine), Extension.js can build your extension into a **Safari** app on macOS. | Target | Usage | | - | - | | **Safari** | `npx extension build --browser=safari` | | **WebKit-based** (engine alias) | `npx extension build --browser=webkit-based` | Safari is a **dev and build target**: `build` and `dev` are supported, but `preview` and `start` are not. `dev` converts your extension, signs an app, opens it, streams logs, and reloads on save, after you enable the extension once in Safari Settings. It requires macOS with the full Xcode app. See [Building Safari extensions](/docs/browsers/safari) for the full workflow, requirements, and how to enable the extension in Safari. ## Multi-browser selection You can run multiple named browsers in one command: ```bash theme={null} npx extension dev --browser=chrome,firefox ``` Use comma-separated values to run multiple named targets in sequence (for example, `--browser=chrome,edge,firefox`). ## Constraints and behavior * `chromium-based` requires `--chromium-binary` in commands that launch a browser (`dev`, `start`, `preview`); `build` needs no binary. * `gecko-based` / `firefox-based` require `--gecko-binary` under the same conditions. * Engine-based targets route to the same Chromium/Firefox runners with engine-aware behavior. * As `build` targets, engine targets get their own `dist/` folder, `.env.` resolution, `EXTENSION_BROWSER` value, and manifest prefix. See [What engine targets mean for `build`](/docs/commands/build#what-engine-targets-mean-for-build). ## Firefox builds warn about Chromium-only APIs From 4.1.18, a production build for a Gecko target scans the emitted bundle for two calls that addons-linter reports as `UNSUPPORTED_API`: `chrome.sidePanel.*` on any manifest version, and `chrome.action.*` on Manifest V2. Each hit prints a warning that names the file. The build still succeeds. ```plaintext theme={null} background.ts uses chrome.sidePanel, which is Chromium only. Firefox opens a sidebar through the sidebar_action manifest key on every manifest version, and addons-linter flags the call as UNSUPPORTED_API. Move the call behind a build-time branch on import.meta.env.EXTENSION_PUBLIC_BROWSER so the Firefox bundle drops it. ``` ```plaintext theme={null} background.ts uses chrome.action, which Manifest V2 does not have on Firefox. Firefox Manifest V2 exposes the toolbar button as browserAction, and addons-linter flags the call as UNSUPPORTED_API. Use browserAction behind a build-time branch on import.meta.env.EXTENSION_PUBLIC_BROWSER, or declare Manifest V3 for Firefox with firefox:manifest_version. ``` The fix is a branch that the bundler resolves at build time, so the Firefox bundle drops the call entirely: ```js theme={null} if (import.meta.env.EXTENSION_PUBLIC_BROWSER !== "firefox") { chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }); } ``` On 4.1.39 and earlier, a runtime guard such as `chrome.sidePanel?.setPanelBehavior()` still warns. From the release after 4.1.39, a call that Firefox never reaches does not warn. That covers a call behind `if (chrome.sidePanel)`, a call written as `chrome.sidePanel?.setPanelBehavior()`, and a call behind a `typeof chrome.sidePanel !== "undefined"` check. The Safari warning reads the same guards, see [Safari](/docs/browsers/safari#the-one-call-that-kills-a-safari-background). A runtime guard quiets the build warning only. addons-linter matches the static read of the namespace, not what runs. Only a build-time branch on `import.meta.env.EXTENSION_PUBLIC_BROWSER` drops the call from the Firefox bundle, and that is what clears the `UNSUPPORTED_API` finding in the [store check](/docs/commands/build#store-check-for-firefox-builds). See [Environment variables](/docs/features/environment-variables) for the `EXTENSION_PUBLIC_BROWSER` value on each target. ## Best practices * **Use named browsers for daily iteration**: `chrome`, `edge`, and `firefox` are the fastest path for regular testing. * **Use engine-based mode intentionally**: Prefer `chromium-based` / `gecko-based` when validating custom binaries or shipping a family-generic build. * **Keep profiles isolated per browser**: Reduce cross-browser state leakage while debugging. * **Pair with browser-specific fields**: Use browser-prefixed manifest keys for true behavior differences. ## Next steps * [Customize browser flags](/docs/browsers/browser-flags). * [Customize browser preferences](/docs/browsers/browser-preferences). * [Run other browsers from custom binaries](/docs/browsers/running-other-browsers). * [Build Safari extensions on macOS](/docs/browsers/safari). # Browser targeting for Chrome, Firefox, Edge Source: https://extension.js.org/docs/browsers/index Configure browser targets for Chrome, Firefox, and Edge extension development. Covers targeting, profiles, flags, and custom binaries in Extension.js. Run one extension codebase across Chrome, Edge, Firefox, and custom binaries with explicit browser targeting workflows. ## Chrome extension development For Chrome extension development, target `chrome` (or `chromium` for the default Chromium binary): `extension dev --browser=chrome`. Extension.js loads the extension into a fresh, isolated profile and applies a sane set of [Chrome launch flags](/docs/browsers/browser-flags) so reload behavior is predictable. ## Firefox extension development For Firefox extension development, target `firefox`: `extension dev --browser=firefox`. Manifest V3 background scripts compile to a non-persistent `scripts` array (Firefox does not use `service_worker`), and Firefox preferences replace the Chromium concept of `chrome://flags`. See [Browser preferences](/docs/browsers/browser-preferences). ## Edge extension development For Edge extension development, target `edge`: `extension dev --browser=edge`. Edge shares the Chromium engine, so most flags and APIs match Chrome, but Extension.js still emits a separate `dist/edge` artifact for distribution. ## Cross-browser extension development For cross-browser extension development, run multiple targets in one command (`extension dev --browser=chrome,firefox`) and keep browser differences in [browser-prefixed manifest fields](/docs/features/browser-specific-fields). One project, one `manifest.json`, distinct outputs per browser. See [Cross-browser compatibility](/docs/features/cross-browser-compatibility) for the full pipeline. You can also run two dev sessions concurrently, one terminal per browser. Session state (ready contract, control channel, logs, profile) is keyed per browser, so a Chrome session and a Firefox session never collide. See [Session artifacts](/docs/concepts/session-artifacts) for the on-disk layout. ## What to read first | Need | Read this | | - | - | | Choose browser targets quickly | [Browsers available](/docs/browsers/browsers-available) | | Customize launch behavior | [Browser flags](/docs/browsers/browser-flags) | | Configure Firefox preferences | [Browser preferences](/docs/browsers/browser-preferences) | | Control profile isolation | [Browser profile](/docs/browsers/browser-profile) | | Run Brave or custom binaries | [Running other browsers](/docs/browsers/running-other-browsers) | | Develop under WSL | [WSL support](/docs/browsers/wsl) | ## Practical target strategy 1. Use named targets (`chrome`, `edge`, `firefox`) for daily checks. 2. Use comma-separated targets for release validation. 3. Use engine targets only when you need custom binaries. 4. Keep browser differences in browser-prefixed manifest fields. ## Next steps * Learn manifest filtering in [Cross-browser compatibility](/docs/features/cross-browser-compatibility). * Configure browser-specific keys in [Browser-specific manifest fields](/docs/features/browser-specific-fields). # Running other browsers from binary path Source: https://extension.js.org/docs/browsers/running-other-browsers Use your installed Chrome, Brave, Vivaldi, Waterfox or Firefox instead of a managed download by giving Extension.js an explicit binary path. Run popular Chromium and Gecko forks either by name (Extension.js locates the installed binary for you) or by providing an explicit binary path. Test Brave, Opera, Vivaldi, Yandex, Waterfox, and LibreWolf from the same Extension.js workflow. Name the fork directly, or point at any custom binary with binary flags and `extension.config.*` in `dev`, `start`, and `preview`. ## Run a fork by name These forks are first-class browser targets. Pass the name to `--browser` and Extension.js finds the installed binary on your system automatically, running it through its engine family's launcher: | Browser target | Engine family | Auto-located | | - | - | - | | `brave` | Chromium | yes | | `opera` | Chromium | yes | | `vivaldi` | Chromium | yes | | `yandex` | Chromium | yes | | `waterfox` | Gecko | yes | | `librewolf` | Gecko | yes | ```bash theme={null} npx extension@latest dev --browser=brave ``` ```bash theme={null} npx extension@latest dev --browser=waterfox ``` If the browser is not installed, Extension.js exits with install guidance. A named fork inherits its family's manifest keys, so `chromium:`/`firefox:` prefixed fields resolve correctly (see [Browser-specific manifest fields](/docs/features/browser-specific-fields)). > [!NOTE] > > The `dev`, `build`, `start`, and `preview` help output all list every fork > name. The `start` and `preview` lists leave out `safari` and `webkit-based` > because those two commands refuse Safari targets by design. ## Run a custom binary To run a browser without a built-in locator, or to override the located binary, use one of these flags: * `--chromium-binary ` * `--gecko-binary ` (alias: `--firefox-binary `) These binary flags override which browser binary Extension.js launches, regardless of the named browser target you selected. ## Binary capabilities | Option / key | What it does | | - | - | | `--chromium-binary ` | Launches a custom Chromium-family browser binary. | | `--gecko-binary ` | Launches a custom Gecko-family browser binary. | | `--firefox-binary ` | Alias of `--gecko-binary`. | | `browser..chromiumBinary` | Sets default custom Chromium binary in config. | | `browser..geckoBinary` | Sets default custom Gecko binary in config. | | `commands..chromiumBinary` | Sets command-specific custom Chromium binary. | | `commands..geckoBinary` | Sets command-specific custom Gecko binary. | ### CLI examples ```bash theme={null} npx extension@latest dev --browser=chromium-based --chromium-binary="/path/to/brave" ``` ```bash theme={null} npx extension@latest dev --browser=firefox --gecko-binary="/path/to/firefox-developer-edition" ``` You can also use them with `start` and `preview`. ## Find the binary path per OS The binary flags expect an executable file. An invalid path fails fast with an error instead of launching. ### macOS On macOS, an app such as `/Applications/Brave Browser.app` is a folder, not an executable. Pass the executable inside the bundle, at `Contents/MacOS`: ```bash theme={null} npx extension@latest dev --browser=chromium-based --chromium-binary="/Applications/Brave Browser.app/Contents/MacOS/Brave Browser" ``` The executable name can differ from the app name. List the folder to find it: ```bash theme={null} ls "/Applications/Brave Browser.app/Contents/MacOS" ``` ### Windows Quote the path and use forward slashes, which every shell accepts: ```bash theme={null} npx extension@latest dev --browser=chromium-based --chromium-binary="C:/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe" ``` Backslashes also work, but many shells require you to double them, as in `C:\\Program Files\\...`. ### Linux Pass the executable that your package manager installed: ```bash theme={null} npx extension@latest dev --browser=chromium-based --chromium-binary="/usr/bin/brave-browser" ``` Run `which brave-browser` to print the path when the binary is on your `PATH`. [Extension.js: run Brave with --chromium-binary](https://www.youtube-nocookie.com/embed/ihOvYKwT4sE?rel=0) ## Configure in `extension.config.*` ```js theme={null} export default { browser: { "chromium-based": { chromiumBinary: "/path/to/custom-chromium-browser", }, "gecko-based": { geckoBinary: "/path/to/custom-gecko-browser", }, }, }; ``` You can also place binary paths in command blocks: ```js theme={null} export default { commands: { dev: { chromiumBinary: "/path/to/custom-chromium-browser", }, preview: { geckoBinary: "/path/to/custom-gecko-browser", }, }, }; ``` ## Target mapping behavior Binary hints map to engine targets: * `chromiumBinary` → `chromium-based` * `geckoBinary` / `firefoxBinary` → `gecko-based` If you provide both, Extension.js applies Chromium binary resolution first. ## Available browsers Forks with a built-in locator run by name; anything else runs with a binary flag: | Browser name | Type | How to run | Official website | | - | - | - | - | | **Brave** | Chromium-based browser | `--browser=brave` or `--chromium-binary` | [brave.com](https://brave.com) | | **Opera** | Chromium-based browser | `--browser=opera` or `--chromium-binary` | [opera.com](https://www.opera.com) | | **Vivaldi** | Chromium-based browser | `--browser=vivaldi` or `--chromium-binary` | [vivaldi.com](https://vivaldi.com) | | **Yandex** | Chromium-based browser | `--browser=yandex` or `--chromium-binary` | [browser.yandex.com](https://browser.yandex.com) | | **Waterfox** | Gecko-based browser | `--browser=waterfox` or `--gecko-binary` | [waterfox.com](https://www.waterfox.com) | | **LibreWolf** | Gecko-based browser | `--browser=librewolf` or `--gecko-binary` | [librewolf.net](https://librewolf.net) | | **Zen** | Gecko-based browser | `--browser=zen` or `--gecko-binary` | [zen-browser.app](https://zen-browser.app) | | **Floorp** | Gecko-based browser | `--browser=floorp` or `--gecko-binary` | [floorp.app](https://floorp.app) | | **Firefox Developer Edition** | Gecko-based browser | `--gecko-binary` | [firefox.com](https://www.mozilla.org/firefox/developer/) | ## Important constraints * `chromium-based` requires `--chromium-binary` (or `chromiumBinary` in config). Without it the launch hard-exits with an error. There is no fallback to a system browser. * `gecko-based` / `firefox-based` require a valid `geckoBinary` path. * `librewolf` needs remote debugging turned on once per machine. LibreWolf resets `devtools.debugger.remote-enabled` to `false` at every start, which overrides the profile Extension.js creates, so the launch checks `~/.librewolf/librewolf.overrides.cfg` (`%USERPROFILE%\.librewolf\librewolf.overrides.cfg` on Windows) and stops with the two lines to add when they are missing: ```text theme={null} pref("devtools.debugger.remote-enabled", true); pref("devtools.debugger.prompt-connection", false); ``` * Invalid paths fail fast with a clear CLI/runtime error. * `build` does not accept binary flags. You can use binary-based launching only with `dev`, `start`, and `preview`. ## Binary variables Set an environment variable to launch a named target from a specific binary, without touching config: ```bash theme={null} EDGE_BINARY="/path/to/msedge" npx extension@latest dev --browser=edge ``` ```bash theme={null} FIREFOX_BINARY="/path/to/firefox" npx extension@latest dev --browser=firefox ``` | Browser | Variables, in the order that they are read | | - | - | | `chrome` | `CHROME_FOR_TESTING_PATH`, `CHROMIUM_BINARY`, `CHROME_BINARY` | | `chromium` | `CHROMIUM_BINARY` | | `edge` | `EDGE_BINARY` | | `firefox` | `FIREFOX_BINARY` | From the release after 4.1.39, every browser resolves its binary in one order. The flag comes first, then the variable, the managed binary, and the system install. If the path does not exist or cannot run, the launch fails with `E_BROWSER_BINARY_INVALID` instead of silently falling back. The identity card names the variable that chose the binary, as in `(pinned with EDGE_BINARY)`. See [How the binary is chosen](/docs/browsers/browsers-available#how-the-binary-is-chosen). ## Run without launching a browser Sometimes the right browser count is zero, for example in containers, over SSH, or when you drive a browser yourself. Pass `--no-browser` to `dev`, `start`, or `preview`: ```bash theme={null} npx extension@latest dev --no-browser ``` The dev loop stays complete. The server watches your files, and every rebuild broadcasts a reload. After the first successful compile, the terminal prints a `(no-browser mode)` banner that names the output folder. Load that `dist/` folder into a browser that you already run. In Chromium browsers, choose "Load unpacked" at `chrome://extensions` with Developer mode on. The loaded extension keeps updating on save. See [`dev`](/docs/commands/dev) for readiness synchronization with `--wait`. To make this the default for a command, set `noBrowser` in config. The CLI flag wins over the config value: ```js theme={null} export default { commands: { dev: { noBrowser: true, }, }, }; ``` ## Opt out of injected defaults `dev`, `start`, and `preview` inject launch defaults into every session. One visible default is dark appearance. Chromium targets get the `--force-dark-mode` and `--enable-features=WebUIDarkMode` flags. Gecko targets get the matching dark preferences. To keep your system appearance, list the flag in `excludeBrowserFlags`: ```js theme={null} export default { browser: { "chromium-based": { chromiumBinary: "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser", excludeBrowserFlags: ["--force-dark-mode"], }, }, }; ``` Excluding `--force-dark-mode` drops the whole appearance bundle, including the Gecko preferences. An exclude entry also matches by switch name, so `--enable-features` removes `--enable-features=WebUIDarkMode`. See [Browser flags](/docs/browsers/browser-flags) for the default flag list and the full exclusion rules. ## Best practices * **Pair binaries with explicit browser target**: Use `--browser=chromium-based` or `--browser=gecko-based` for predictable intent. * **Use absolute paths**: Avoid shell-dependent path resolution issues. * **Version-pin in continuous integration (CI) runners**: Keep browser binary paths deterministic for automated checks. * **Combine with profile/flags carefully**: Reuse the same profile and flag strategy used for named browser targets. ## Next steps * Learn more about [Browser preferences](/docs/browsers/browser-preferences). * Learn more about [Browser profile](/docs/browsers/browser-profile). # Building Safari extensions with Extension.js Source: https://extension.js.org/docs/browsers/safari Develop and build your web extension as a Safari app on macOS with Extension.js. Covers requirements, the dev loop, logs, reload, and known limitations. Develop a web extension against Safari on macOS, with no separate Xcode project to maintain by hand. > [!NOTE] > > Safari is supported on **macOS only** and requires the full Xcode app. `dev` > and `build` both work. `preview` and `start` do not, for the reason described > in [Command support](#command-support). `extension dev --browser safari` bundles your code, converts it with Apple's `safari-web-extension-converter`, builds and signs an app with `xcodebuild`, and opens it. You enable the extension once in Safari Settings. After that, `extension logs` streams background and content rows, the control bridge attaches, and every save reloads the extension in Safari. That dev loop ships from 4.1.20. > [!NOTE] > > The behavior on this page was measured on macOS 26.5.2, Safari 26.5.2, and > Xcode 26.6. Safari 27 exists and was not re-measured. [Extension.js: extension build --browser=safari](https://www.youtube-nocookie.com/embed/Z9KqTxWxTYQ?rel=0) ## What you need Safari is **macOS only** and needs the **full Xcode app**, not just the Command Line Tools. The converter (`safari-web-extension-converter`) and `xcodebuild` ship inside `Xcode.app`. ```bash theme={null} # Install Xcode from the Mac App Store, then point the toolchain at it: sudo xcode-select --switch /Applications/Xcode.app xcodebuild -runFirstLaunch ``` A paid Apple Developer account is **not** required. Without `--development-team` the app is signed ad-hoc. Safari lists and runs an ad-hoc build only while **Allow unsigned extensions** is on in Safari ▸ Settings ▸ Developer (the Develop menu on older Safari). Safari turns that setting off each time it quits. See [Ad-hoc builds](#ad-hoc-builds-no-apple-developer-account). If Xcode is missing, `extension dev` and `extension build` for Safari targets fail fast, before bundling, with guidance instead of a late, confusing error. ## What it produces `extension build --browser=safari` creates, next to your project: | Path | What it is | | - | - | | `dist/safari` | The bundled web extension (manifest, scripts, assets). | | `dist/safari-xcode` | The generated Xcode project (app + Safari extension targets). | | `…/Release/.app` | The compiled app that hosts your extension, signed with your team id when `--development-team` is set and ad-hoc otherwise. | The pipeline runs end to end: **bundle → convert → `xcodebuild`**, plus **open the app → guided enable** in `dev` (or with `build --open`). A plain `build` stops after packaging and prints the `open` command instead. ```bash theme={null} npx extension build --browser=safari ``` The app name and bundle identifier are derived from your manifest `name` (for example, `React Sidebar Example` → bundle id `dev.extensionjs.React-Sidebar-Example`). The project targets macOS by default. > [!WARNING] > > The generated `dev.extensionjs.*` bundle id is a development placeholder. If > you plan to distribute your app, set a bundle id you own **from the first > build**. Changing it later makes Safari treat the extension as a brand-new > identity (users lose their enable state and data). ## App identity and packaging options Both `dev` and `build` accept identity overrides (Safari targets only): | Flag | What it does | | - | - | | `--bundle-id` | User-owned reverse-DNS bundle identifier (e.g. `com.example.my-extension`). | | `--app-name` | Override the app name (defaults to the manifest `name`). | | `--development-team` | Apple Developer team id to sign with (e.g. `A1B2C3D4E5`). Without it the build is ad-hoc signed. | | `--app-icon` | A square PNG, ideally 1024 px, used as is for the Safari app icon instead of the manifest icon on a white plate. Needs 4.1.39 or later. | | `--macos-only` | Generate a macOS-only Xcode project (default `true`). Pass `--macos-only false` for a universal macOS + iOS project. | | `--force-regenerate` | Regenerate the Xcode project even when it is up to date. | | `--safari-binary` | `dev` only: the Safari binary to open after packaging. | | `--open` | `build` only: open the built app after packaging (off by default). | Without `--bundle-id`, Extension.js derives `dev.extensionjs.`, where `` is your sanitized app name (non-alphanumeric runs become hyphens). A user-provided bundle id must be reverse-DNS shaped: at least two dot-separated segments of letters, digits, and hyphens, each starting with a letter. Invalid values are rejected before packaging. The same options can live in `extension.config.js` (CLI flags win): ```js theme={null} export default { browser: { safari: { appName: "My Extension", bundleId: "com.example.my-extension", developmentTeam: "A1B2C3D4E5", appIcon: "./assets/app-icon-1024.png", }, }, }; ``` Changing the bundle id, app name, or manifest regenerates the Xcode project on the next run (see the regeneration warning below). ## Building the web-extension bundle on other platforms `extension build --browser=safari` works on Linux and Windows too: it produces the complete `dist/safari` web-extension bundle and **skips the Xcode packaging step** with a warning. This lets CI build the payload anywhere and a Mac (or a macOS runner) do the convert + `xcodebuild` part later. `dev --browser=safari` still requires macOS with Xcode, because a Safari dev loop without packaging has nothing to run. ## Enabling the extension in Safari Extension.js prints the steps that match your build when the app opens (`dev`, or `build --open`), and confirms when macOS has registered the extension. The one-time gesture is the same for signed and ad-hoc builds: 1. Safari ▸ Settings ▸ Extensions ▸ turn on your extension. The toggle survives Safari restarts, so this is genuinely one time per machine, not once per launch. An ad-hoc build also needs **Allow unsigned extensions** on after each Safari launch. Turning the extension **on is not the same as giving it access to pages**. Safari asks for website access separately, and until you grant it a content script does not run at all: the extension is listed, enabled, and does nothing. This holds even when your manifest declares `` in both `content_scripts.matches` and `host_permissions`, which is the part that surprises people coming from Chrome, where installing grants it. In the same panel, under **Permissions**, use: * **Always Allow on Every Website…** for an extension that you iterate on. It persists, so you grant it once. * **Edit Websites…** to allow only the hosts that you are testing against. If your extension loads but nothing happens on the page, this is almost always why. Check the permission before you go looking at your code. ### Let `dev` turn it on `--enable-extension` does both steps for you through macOS Accessibility. Your terminal app needs a one-time Accessibility grant. ```bash theme={null} npx extension@latest dev --browser safari --enable-extension ``` Quit Safari before you start. The run asks `safaridriver` for its WebDriver session first, then turns the extension on in the Safari that the session opened. Safari 27 does not answer a session request while another Safari is open. In that case the run turns the extension on without a session, and tells you to quit Safari. In the Safari that the session opened, the run grants access with **Always Allow on Every Website…**, because **Edit Websites…** does nothing there. Do not click inside the automation window. Safari then asks whether to stop the session. From the release after 4.1.39, the log names that grant. The line reads ` is on in Safari, allowed on every website.` The run also closes the windows that it opened in that Safari to reach Settings. ### Signed builds with an Apple Developer team Pass `--development-team` with your Apple Developer team id and the app is signed with your own certificate: ```bash theme={null} npx extension@latest dev --browser safari --development-team A1B2C3D4E5 ``` To find your team id, run `xcrun security find-identity -v -p codesigning`. The ten-character code in the certificate name is your team id, and it is also on the Membership page of your Apple Developer account. Team signing is what you need for distribution. For day-to-day development it changes nothing about how Safari lists or runs the extension. ### Ad-hoc builds (no Apple Developer account) Without `--development-team` the app is ad-hoc signed. Safari lists it and runs it only while Safari ▸ Settings ▸ Developer ▸ **Allow unsigned extensions** is **on**. Safari asks for your password when you turn that setting on, and turns it off again when Safari quits. After a relaunch, the extension is missing from Settings ▸ Extensions and no content script runs. Opening the app again does not bring it back. Run `dev` again. From the release after 4.1.39, the run registers the extension again when it opens the app. It repeats that every 5 seconds, for up to 10 minutes, until Safari lists the extension. Turn **Allow unsigned extensions** on in that time, or pass `--enable-extension`, which turns the setting on for you. The extension comes back turned on, with the website access that you granted. This was measured on Safari 27. A team-signed build needs no setting. `dev --enable-extension` clicks that switch for you. Safari 27 treats a scripted click on an ad-hoc row as interference, and asks you to confirm it with Touch ID or your password. The run prints that Safari is waiting, and reads the switch for 60 seconds. A team-signed row takes the same click with no prompt. When nobody answers in that time, the session stops with a reason that quotes the prompt: ```text theme={null} Safari read the switch for off 60 s after the script clicked it, and the macOS password prompt (coreautha) is open and waits for an answer ("Safari detected an app or service that interfered with clicking. Are you sure you want to turn on this Safari Extension? Touch ID to allow this."): answer it in Safari or turn the switch on by hand in Safari > Settings > Extensions, or set browser.safari.developmentTeam in extension.config.js so the build is signed, then run again ``` Answer the prompt, or set `browser.safari.developmentTeam` (or pass `--development-team`) so the next build is signed. The same sentence is in `safari.reason` of [`ready.json`](/docs/contracts/ready-json), with `step` set to `enabled`. ### Temporary extensions (no Xcode) Safari has a second path that Extension.js does not drive: Safari ▸ Settings ▸ Developer ▸ **Add Temporary Extension…**. It loads an unpacked folder such as `dist/safari`, with no Xcode step at all. It needs **Allow unsigned extensions**, and the extension disappears when Safari quits, or after 24 hours. Use it for a quick look at a bundle. Use `extension dev` for a dev loop that survives a restart. ## The dev loop `extension dev --browser=safari` runs a watch loop: ```bash theme={null} npx extension dev --browser=safari ``` * **First compile**: full package: convert, build, open the app, and print the enable steps. * **On every save**: an incremental `xcodebuild` resync updates app resources from the rebuilt `dist/safari`. Safari reloads the extension. Once the extension is enabled, the loop needs no further clicking. Measured on Safari 26.5.2, a save reaches a reloaded extension in roughly 4 seconds. A plain `extension dev --browser safari` opens the container app that the converter built, not Safari itself. Safari is where you enable and use the extension, so open it yourself, or pass `--safari-binary` and the session opens Safari beside the app. Once the extension is enabled and the session runs with `--allow-control`, `extension navigate ` points Safari's active tab at a page through the extension, a static `tabs` call rather than an eval, so a content script's page can be opened without touching the browser by hand. Each save prints what it did. A resync ends with `Rebuilt .`, and a content script change follows it with `Reloading content_script (content.ts)…`. When the extension is not connected at that moment, the line reads `Queued content_script (content.ts) for the extension to apply when it reconnects.` instead. A background or manifest edit prints only `Rebuilt`, because Safari restarts the extension itself after the resync, and there is nothing left to dispatch. After a conversion, the converter's own warning list is printed, one line per manifest key that it does not know. A key that the build keeps on purpose is annotated under `Extension.js kept one of these keys on purpose:`. Today that is `world`, with the reason `Safari has honored the MAIN world since Safari 18, so the key stays`. In dev, the bridge parks early errors. An error thrown before the extension's socket to the dev server opens is stored in the extension's `chrome.storage.local` under `__extjsPendingErrors` and replayed once the socket connects, so `extension logs` still shows it. ### What one save costs Resyncs run in the background, so the bundler loop is never blocked. A burst of saves collapses to a single follow-up resync against the newest output, so five quick saves cost one rebuild, not five. If the first full package fails, the next compile retries the full flow instead of resyncing a project that was never built. ### When the Xcode project regenerates The Xcode project is generated once and reused for resyncs. Staleness is decided by a fingerprint file, `dist/safari-xcode/.manifest-fingerprint`. The v4 fingerprint, written from 4.1.20, stores the identity inputs (app name, bundle id, and the macOS-only setting), the top-level entries of `dist/safari`, and the manifest `icons` set. Of the manifest itself it stores only the surface the converter judges. That surface is the top-level key names, the `permissions` and `optional_permissions` values, and the key names inside each `content_scripts` entry and `options_ui`. The other manifest bytes stay out, so the content-hashed script names that change on every save do not re-run the converter. The converter runs again when the stored fingerprint no longer matches, or when you pass `--force-regenerate`. Cosmetic manifest edits (key order, whitespace) do not trigger it. Regeneration replaces the project: customizations made in Xcode (entitlements, capabilities, added files or targets) are **discarded**. Only these signing settings are preserved automatically: `DEVELOPMENT_TEAM`, `CODE_SIGN_STYLE`, and `PROVISIONING_PROFILE_SPECIFIER`. Extension.js warns before every regeneration of an existing project. If you customized the project in Xcode, back it up first. Delete `dist/safari-xcode` for a clean slate. ### How the bundle id is enforced Apple's converter derives the parent app's id from the app name instead of taking `--bundle-identifier` verbatim. After every conversion, Extension.js rewrites both `PRODUCT_BUNDLE_IDENTIFIER` entries in the generated `project.pbxproj`: the app target gets your bundle id, and the extension target gets `.Extension`. This keeps the identity you configured, not the one the converter guessed. ### What `xcodebuild` runs The compile step uses the `Release` configuration with derived data written to `dist/safari-xcode/.derived`, a folder worth adding to `.gitignore`. Signing settings depend on `--development-team`. With a team id the build passes `DEVELOPMENT_TEAM=`, `CODE_SIGN_STYLE=Automatic`, and `-allowProvisioningUpdates`, so Xcode mints the provisioning profile it needs without being opened. Without one it passes ad-hoc settings (`CODE_SIGN_IDENTITY=-`, `CODE_SIGNING_REQUIRED=NO`, `CODE_SIGNING_ALLOWED=YES`) so the embedded `.appex` still validates without an Apple Developer account. The scheme name is your app name for a macOS-only project, and ` (macOS)` for a universal project. ### Registration confirmation After opening the app, Extension.js polls `pluginkit` for the extension's registration, about 6 tries spread over 5 seconds, and prints a confirmation or a not-yet-registered note. Under `--no-open` (and plain `build` without `--open`) the app never launches, so registration cannot happen yet. The poll is skipped and the CLI prints the `open` command instead. ## Reading logs From 4.1.20, a Safari dev session is a normal session for [`logs`](/docs/commands/logs): ```bash theme={null} extension logs --browser safari --follow ``` Background rows and content-script rows arrive in the same stream as they do on Chromium, with the same `--context`, `--level`, and `--output` filters. A silent stream after an edit is the symptom described in the next section. It means the background context is gone, not that logging is unsupported. ## The one call that kills a Safari background One unguarded Chromium-only call at the **top level** of a background script throws on Safari. Safari then discards the background context, and you get no logs, no reload, and no error anywhere. The extension looks dead. ```js theme={null} // Kills the background on Safari: sidePanel does not exist there. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }); ``` Guard the call, or branch at build time: ```js theme={null} // Optional chaining is enough for a call you can skip. chrome.sidePanel?.setPanelBehavior({ openPanelOnActionClick: true }); // A feature check works the same way, and covers everything inside it. if (chrome.sidePanel) { chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }); } // Or keep the code out of the Safari bundle entirely. if (import.meta.env.EXTENSION_PUBLIC_BROWSER !== "safari") { chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }); } ``` The same code inside an event listener is survivable, because only that callback throws. At the top level it takes the whole context with it. The build-time warnings described below exist to catch exactly this, so read them before you start debugging a background that never speaks. See [Environment variables](/docs/features/environment-variables) for the `EXTENSION_PUBLIC_BROWSER` value on each target. ## What Safari builds change in your manifest ### Background page instead of a service worker From 4.1.20, Safari builds emit a non-persistent background **page** (`background: {scripts: [...]}`), not a service worker. Extension.js translates a `background.service_worker` entry into that shape, the same translation it runs for Firefox. The reason is measured, not stylistic. On Safari 26.5.2, a Manifest V3 service worker never started in testing, including for extensions built by Apple's own converter. A background page ran immediately. WebKit deliberately prefers the page form ([WebKit bug 270750](https://bugs.webkit.org/show_bug.cgi?id=270750)). Author one `background.service_worker` and it loads on Chromium, Firefox, and Safari. See [Background scripts](/docs/implementation-guide/background) for the translation in both directions. ### Keys and permissions Safari cannot use Manifest keys and permissions that Safari does not implement are dropped from the Safari build automatically. From 4.1.20, the build prints one line per dropped key, naming the key and why it went. Nothing is dropped silently, and your source `manifest.json` is untouched. `content_scripts[].world` is deliberately **kept**, because Safari has supported it since Safari 18. For Safari-only overrides, use the `safari:` and `webkit:` manifest prefixes. They win over the `chromium:` family keys that Safari otherwise inherits. See [Browser-specific manifest fields](/docs/features/browser-specific-fields). ### APIs Safari does not have From 4.1.20, the build warns about extension APIs that Safari lacks, naming each namespace or member it finds in your code. Twelve namespaces are covered: `sidePanel`, `offscreen`, `tabGroups`, `management`, `identity`, `notifications`, `bookmarks`, `history`, `downloads`, `idle`, `omnibox`, and `userScripts`. The warnings run in production builds and in `dev`. The build also warns on 21 members of namespaces that Safari does ship, where the namespace resolves and the throw waits one level deeper: `action.getUserSettings`, `action.getBadgeTextColor`, `action.setBadgeTextColor`, `action.onUserSettingsChanged`, `storage.managed`, `runtime.getContexts`, `runtime.onSuspend`, `runtime.onSuspendCanceled`, `runtime.onUpdateAvailable`, `declarativeNetRequest.getAvailableStaticRuleCount`, `declarativeNetRequest.getDisabledRuleIds`, `declarativeNetRequest.updateStaticRules`, `declarativeNetRequest.testMatchOutcome`, `declarativeNetRequest.onRuleMatchedDebug`, `tabs.group`, `tabs.ungroup`, `webNavigation.onCreatedNavigationTarget`, `webNavigation.onHistoryStateUpdated`, `webNavigation.onReferenceFragmentUpdated`, `webNavigation.onTabReplaced`, and `windows.onBoundsChanged`. The scan reads the built script. A mention of one of these names in a comment or in a string literal triggers it too. Optional chaining silences it: `chrome.sidePanel?.setPanelBehavior()` for a namespace, and `chrome.tabs.group?.()` for a member. A feature check silences it as well, because Safari never enters the branch. The scan reads `if (chrome.offscreen)`, `globalThis.chrome?.offscreen`, `typeof chrome.offscreen !== "undefined"`, `"offscreen" in chrome`, a negated check followed by `return` or `throw`, and the `&&` and `?:` forms of the same test. One check on any missing API covers every call inside the branch, including a function that only that branch calls, and a `try` block with a `catch` counts as handled. A call that also runs outside the check, or an exported function, still warns. A warning is not a build failure. Code that reaches one of these APIs still ships. It is your call whether to guard it, branch on the target, or accept that the feature is absent on Safari. ## Debugging in Safari Web Inspector covers every extension context, and it is the right tool when you want a debugger rather than a log stream: * **Background**: Safari ▸ Develop ▸ Web Extension Background Content ▸ *your extension*. * **Popup/options/sidebar pages**: open the surface, then right-click ▸ Inspect Element (or Develop ▸ *your Mac* ▸ the page). * **Content scripts**: inspect the host page, where extension script contexts appear in the Sources tab under Extension Scripts. If a build fails, the CLI prints the tail of the failing `xcrun`/`xcodebuild` output, bounded to the last 50 lines and 8 KB so diagnostics stay readable. Pass `--debug` (or set `EXTENSION_DEBUG=true`) to stream the full tool output live instead. ## Engine target `safari` has an engine alias, **`webkit-based`**, that parallels `chromium-based` and `gecko-based`: ```bash theme={null} npx extension build --browser=webkit-based ``` ## Command support | Command | Safari support | | - | - | | `build` | ✅ Builds and packages the Safari app. | | `dev` | ✅ Watch, incremental rebuild, logs, and automatic reload. | | `preview` | ❌ Not supported. Exits with `E_COMMAND_UNSUPPORTED_FOR_TARGET`. | | `start` | ❌ Not supported. Same reason as `preview`. | `preview` and `start` exist to launch an already-built extension in a running browser. The Safari route for that is WebDriver, and it was measured. `safaridriver` does load an unpacked folder, and the background even runs, but Safari grants the extension **zero host origins**. Content scripts never inject, and no API call can grant the access afterwards. A session that looks healthy would test nothing, so both commands refuse Safari targets instead and point at `extension dev --browser safari` or `extension build --browser safari --open`. [Extension.js: extension dev --browser=safari](https://www.youtube-nocookie.com/embed/AqmncRR_tSU?rel=0) ## Limitations * **Packaging is macOS only.** The Xcode step needs the full Xcode app. `build` still produces `dist/safari` elsewhere. * **`preview` and `start` have no Safari path.** See [Command support](#command-support) for what was measured. * **Enabling and granting access need you once.** They are Safari security controls. `dev --enable-extension` scripts both, and Safari can still ask for Touch ID or your password. Both survive restarts. An ad-hoc build also needs **Allow unsigned extensions** on after each Safari launch. * **Signing stops at development.** `--development-team` signs the local app with your development certificate. Distribution signing, notarization, and App Store submission are a separate step beyond this workflow (see below). * **macOS target only.** iOS app generation is not produced by this workflow today. ## Common questions **Can I use only the Xcode Command Line Tools?** No. `xcode-select --install` gives you compilers and `git`, but `safari-web-extension-converter` and the app build in `xcodebuild` ship inside `Xcode.app`. Install Xcode from the Mac App Store, then follow [What you need](#what-you-need). **Can I build for iOS?** Not with this workflow. It builds, signs, and opens the macOS app only. `--macos-only false` asks the converter for a universal macOS and iOS Xcode project. Finishing the iOS side is a manual Xcode job that Extension.js does not run today. ## After dev: shipping to the App Store The Safari workflow above ends with a locally signed app, ad-hoc or development. Distributing it (to the Mac App Store, or as a notarized direct download) is a separate pipeline that Extension.js plans to offer through the [extension.dev](https://extension.dev?utm_source=extension-js-org\&utm_medium=sponsor\&utm_campaign=docs-seam) platform. Until that lands, follow Apple's own guides: * [Distributing your Safari web extension](https://developer.apple.com/documentation/safariservices/safari_web_extensions/distributing_your_safari_web_extension) (Apple Developer Program, signing, App Store Connect). * [Notarizing macOS software](https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution) for non-App Store distribution. Two things from the Extension.js side make that path smooth. Do them early: 1. **Set your own `--bundle-id`** (reverse-DNS, a domain you own) from the first build. Bundle id is the extension's identity on Apple platforms. 2. **Set your `DEVELOPMENT_TEAM` in Xcode once**: it survives project regeneration automatically, along with `CODE_SIGN_STYLE` and `PROVISIONING_PROFILE_SPECIFIER`. ## What a session leaves behind The ready contract at `dist/extension-js/safari/ready.json` carries Safari-specific values: | Field | Value on Safari | | - | - | | `browserPid` | The container app's process id. With `--safari-binary`, Safari's own process id. | | `extensionId` | `.Extension`, the id of the extension target inside the app. | | `runtime` | `attached` once the extension's background connects to the dev server, `detached` after it disconnects. | | `binaryProvenance` | `system` for the container app, `pinned` with `--safari-binary`. | `extension logs`, `extension eval`, `extension reload`, and `extension doctor --browser safari` attach to the session through that contract, the same way they do on Chromium. Ctrl+C stops the dev server only. The container app stays open, Safari stays open, the extension stays registered with macOS and enabled in Safari Settings, and `dist/safari-xcode/` stays on disk. The next `dev` reuses that project. Delete `dist/safari-xcode/` for a clean slate, which makes the next run convert and build from scratch. ## Best practices * **Read the build warnings first.** They name the APIs and manifest keys that Safari does not have, which is the cheapest way to find a background that will not start. * **Guard Chromium-only calls at the top level** of background and content scripts, with optional chaining or a branch on `EXTENSION_PUBLIC_BROWSER`. * **Use browser-specific fields** for true behavioral differences. Safari resolves the `chromium:` family prefix, and `safari:`/`webkit:` prefixed keys win over it on Safari targets, for both `--browser=safari` and `--browser=webkit-based`. `chrome:` and `edge:` keys do not reach Safari. * **Keep the generated project** unless you need a clean slate, because regenerating discards Xcode-side customizations beyond the preserved signing settings. ## Next steps * See all [supported browsers](/docs/browsers/browsers-available). * Stream a Safari session with [`logs`](/docs/commands/logs). * Use [browser-specific manifest fields](/docs/features/browser-specific-fields). * Review [multi-platform builds](/docs/features/multi-platform-builds). # Developing extensions under WSL Source: https://extension.js.org/docs/browsers/wsl Run Extension.js dev sessions inside Windows Subsystem for Linux (WSL), covering Linux browser detection, the Windows .exe fallback, and Chrome wrapper scripts. Run the full Extension.js dev loop inside Windows Subsystem for Linux (WSL), with the browser resolved automatically from either side of the boundary. Extension.js detects WSL through the `WSL_DISTRO_NAME`, `WSL_INTEROP`, or `WSLENV` variables, or a Microsoft kernel signature. It then resolves a browser binary with a fixed ladder. ## The resolution ladder 1. **A Linux-native browser first.** When a GUI display is available (`DISPLAY` or `WAYLAND_DISPLAY` is set), Extension.js checks known Linux install locations. Examples are `/opt/google/chrome/chrome`, `/usr/bin/chromium`, `/snap/bin/chromium`, and `/usr/bin/firefox`. A Linux browser keeps the whole dev loop on the Linux side. 2. **A Windows `.exe` under `/mnt/c` as fallback.** When no Linux browser exists, Extension.js looks for the Windows install. It checks `/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`, the matching Chromium, Edge, and Firefox paths, and their `Program Files (x86)` variants. 3. **A spawn-time retry.** If the chosen binary fails to spawn, Extension.js retries once with the Windows binary before giving up. You can skip the ladder entirely by passing an explicit path: ```bash theme={null} npx extension@latest dev --browser=chromium-based --chromium-binary="/mnt/c/Program Files/Google/Chrome/Application/chrome.exe" ``` ## The Chrome wrapper-script swap On Linux, `google-chrome` and its channel variants are shell wrapper scripts, not the real binary. The wrapper closes extra file descriptors when it execs Chrome, which breaks the `--remote-debugging-pipe` channel the dev session depends on. Under WSL with a GUI, Extension.js detects a wrapper by name (`google-chrome`, `google-chrome-stable`, `google-chrome-beta`, `google-chrome-dev`, `google-chrome-unstable`) and swaps it for the real binary at `/opt/google/chrome/chrome` when that file exists. Known install locations already list real binaries before wrappers for the same reason. ## Shell aliases are not paths > [!WARNING] > > Extension.js launches browsers with `child_process.spawn`, which never reads > your shell configuration. A shell alias like `google-chrome=...` does not > exist for the launcher. Pass a real file path, or a wrapper script that is an > actual executable on disk. ## When nothing is found If neither side has a browser, the CLI exits with WSL-specific guidance: install a Linux browser inside WSL, or point `--chromium-binary` at the Windows `.exe`. Firefox resolves the same way through its own ladder (`/usr/bin/firefox`, `/snap/bin/firefox`, `/opt/firefox/firefox`, then `/mnt/c/Program Files/Mozilla Firefox/firefox.exe`). ## Next steps * Choose a target in [Browsers available](/docs/browsers/browsers-available). * Point at custom binaries in [Running other browsers](/docs/browsers/running-other-browsers). # Build command for production extensions Source: https://extension.js.org/docs/commands/build Create production-ready extension artifacts for Chrome, Edge, or Firefox with the Extension.js build command. Supports multi-browser and zip output. Create production extension artifacts for one or more browser targets. `build` compiles your extension in production mode and writes output to `dist/`. For monorepo/submodule projects, see [Environment variables](/docs/features/environment-variables#how-it-works) for configuration-time env resolution (project root first, then workspace-root fallback). ## When to use `build` * Preparing extension packages for Chrome Web Store, Edge Add-ons, or Firefox Add-ons. * Running continuous integration (CI) jobs that produce repeatable production artifacts. * Validating production bundle output and browser-target differences before submission. ## Build command capabilities | Capability | What it gives you | | - | - | | Production compilation | Generate optimized extension artifacts per target | | Multi-target output | Build multiple browser targets in one command | | Packaging support | Create distribution zip artifacts with optional source bundle | | CI-friendly behavior | Keep build outputs and naming predictable in automation | ## Usage ```bash npm theme={null} extension build [project-path] [options] ``` ```bash pnpm theme={null} extension build [project-path] [options] ``` ```bash yarn theme={null} extension build [project-path] [options] ``` ```bash bun theme={null} extension build [project-path] [options] ``` ```bash deno theme={null} extension build [project-path] [options] ``` ## Build output After running `build`, Extension.js generates optimized files for the selected browser targets. Output goes to `dist/` with one subfolder per target. Each folder contains bundled JavaScript, CSS, HTML, and required runtime assets. > [!NOTE] > > For TypeScript projects, `build` also regenerates the `extension-env.d.ts` > ambient type declarations (the same file [`dev`](/docs/commands/dev) writes), > so a CI `tsc --noEmit` stays clean whether or not you ran `dev` first. > JavaScript-only projects skip this step. **Example output structure:** ```plaintext theme={null} dist/ ├── chrome/ │ ├── manifest.json │ ├── background/service_worker.js │ ├── content_scripts/content-0.js ├── edge/ │ ├── manifest.json │ ├── background/service_worker.js │ ├── content_scripts/content-0.js ``` ## Building beside a dev session `extension dev` and `extension build` both write `dist/`. When a dev session is running for the same browser, a build into that folder is refused with `E_DEV_SESSION_DIST_SHARED`, and nothing is written. The message names the session's process id and points to `--out-dir`. To test or package a production build while the dev window stays open, pass `--out-dir`. The build writes `/` and puts its zips in `/`: ```bash theme={null} npx extension@latest build --out-dir build --zip ``` That writes `build/chrome` and `build/--chrome.zip`, and `dist/chrome` stays as the dev session left it. The same setting goes in `extension.config.js` as `commands.build.outDir`. ## Browser target matrix | Target style | Examples | Notes | | - | - | - | | Named targets | `chromium`, `chrome`, `edge`, `firefox` | Build one specific browser target | | Engine targets | `chromium-based`, `gecko-based`, `firefox-based` | Family-generic artifacts. See [below](#what-engine-targets-mean-for-build) | | Multi-target | `chrome,firefox` | Comma-separated targets | ### What engine targets mean for `build` `build` never launches a browser, so engine targets don't point at a binary here, but they still produce a distinct artifact, not a renamed copy of a named-target build: * **Own output folder.** `--browser=chromium-based` writes to `dist/chromium-based`, the same folder `dev`, `preview`, and `start` use for that target, so a project developed against a custom Chromium binary builds to matching paths. * **Own env resolution.** `.env.chromium-based` and `.env.chromium-based.production` win over the family's `.env.chromium`/`.env.chrome`/`.env.edge`, and bundled code sees `EXTENSION_BROWSER === "chromium-based"`, so code and config can branch on "generic Chromium" vs a specific store build. * **Own manifest prefix.** `chromium-based:` keys in `manifest.json` resolve as the most-specific match for this target, on top of the family-wide `chromium:` keys. `chrome:` and `edge:` keys do not apply. `gecko-based` works the same way relative to `firefox`. No browser binary is required, and `--chromium-binary`/`--gecko-binary` only matter for commands that launch a browser. ## Arguments and flags | Flag | Alias | What it does | Default | | - | - | - | - | | `[path]` | - | Builds a local extension project. | `process.cwd()` | | `--browser ` | - | Browser/engine target (`chromium`, `chrome`, `edge`, `firefox`, `safari`, engine aliases, or comma-separated values). | `commands.build.browser`, else `chromium` | | `--polyfill [boolean]` | - | Enables `browser.*` API compatibility polyfill for Chromium targets. | `false` | | `--no-polyfill` | - | Disables the cross-browser polyfill. | polyfill disabled | | `--zip [boolean]` | - | Creates a packaged zip artifact in any mode. | `false` | | `--zip-source [boolean]` | - | Includes source files in zip output. | `false` | | `--zip-filename ` | - | Names both the distribution and the source archive. The browser is always appended to the distribution name. | sanitized extension name, version and browser | | `--zip-dir ` | - | From the release after 4.1.39. Writes the ZIP files to this folder, relative to the project root or absolute. See [Zip behavior](#zip-behavior). | the folder that holds `dist/` | | `--source-maps [boolean]` | - | From the release after 4.1.39. Writes a `.map` file beside each script and stylesheet of a production build. The maps stay out of the ZIP file. See [Source maps for a production build](#source-maps-for-a-production-build). | `false` | | `--out-dir ` | - | Writes the build to `/` instead of `dist/`, relative to the project root, so a production build can sit beside a dev session that serves `dist`. A build into the folder a live dev session serves is refused with `E_DEV_SESSION_DIST_SHARED`, see [Building beside a dev session](#building-beside-a-dev-session). | `dist` | | `--silent [boolean]` | - | Suppresses build logs. | `false` | | `--addon-lint [boolean]` | - | Checks Firefox production builds against addons.mozilla.org rules with addons-linter when it is installed. Findings print as warnings. See [Store check for Firefox builds](#store-check-for-firefox-builds). | `true` | | `--no-addon-lint` | - | Skips the addons.mozilla.org check. | check enabled | | `--minify [boolean]` | - | Minifies first-party code in production builds. See [Readable output for Opera Add-ons](#readable-output-for-opera-add-ons). | `true`, `false` for `opera` | | `--no-minify` | - | Ships readable first-party code. | minified, except `opera` | | `--mode ` | - | Bundler mode override (`development`, `production`, or `none`). Also sets `NODE_ENV`. | `production` | | `--extensions ` | - | Comma-separated companion extensions or store URLs. | unset | | `--install [boolean]` | - | Internal flag. Install project dependencies when missing. Lifecycle scripts stay disabled unless `EXTENSION_ALLOW_INSTALL_SCRIPTS=true`. | installs when `node_modules` is missing | | `--output ` | - | Result format. `json` prints a schema-1 envelope on stdout. | `pretty` | | `--debug` | - | Enable maintainer diagnostics. | disabled | `--author` and `--author-mode` are hidden, deprecated aliases for `--debug`. ### Safari flags These flags apply to `safari` and `webkit-based` targets only. Passing any of them with another target exits with an error, so a typo never no-ops silently. | Flag | What it does | Default | | - | - | - | | `--open [boolean]` | Open the built Safari app after packaging. `build` never opens it unless you ask. | `false` | | `--app-name ` | Override the Safari app name. | the manifest `name` | | `--bundle-id ` | User-owned bundle identifier in reverse-DNS form. A malformed value fails before any build. | a generated `dev.extensionjs.*` id | | `--development-team ` | Apple Developer team id to sign the Safari app with. Without it the build is ad-hoc signed, which Safari accepts and lists normally. | unset (ad-hoc signed) | | `--app-icon ` | Build the Safari app icon from this square PNG, ideally 1024 px, used as is. Without it, the icon is the manifest icon on a white plate, so a tile-shaped icon ends up as a tile inside a tile. | the plated manifest icon | | `--macos-only [boolean]` | Generate a macOS-only Xcode project. Pass `false` for a universal macOS + iOS project. | `true` | | `--force-regenerate` | Regenerate the Safari Xcode project even when up to date. | disabled | Safari packaging runs a preflight before the build. On a non-macOS host, `build` warns and skips the Safari packaging step but still compiles the bundle. On macOS with a broken or missing Xcode, the failure is fatal. ## Shared global options Also supports [Global flags](/docs/workflows/global-flags). ## Mode override `--mode` overrides the bundler mode and `NODE_ENV` for the build. Accepts `development`, `production`, or `none`. Use it to mirror Vite/webpack workflows where you need a non-production bundle for staging or debugging. ```bash npm theme={null} npx extension@latest build ./my-extension --mode development ``` ```bash pnpm theme={null} pnpx extension@latest build ./my-extension --mode development ``` ```bash yarn theme={null} yarn dlx extension@latest build ./my-extension --mode development ``` ```bash bun theme={null} bunx extension@latest build ./my-extension --mode development ``` ```bash deno theme={null} deno run -A npm:extension@latest build ./my-extension --mode development ``` Invalid values exit with an error. The default remains `production`. A development-mode build is shippable. It keeps the CSP and permissions you wrote in the manifest, injects no reload client, and its zip carries no source maps (the `.map` files stay in `dist/` for you). Only `extension dev` turns the dev instrumentation on. `--zip` packages the output in any mode, not only `production`. ## Zip behavior | Option | Effect | Typical use | | - | - | - | | `--zip` | Creates a packaged artifact zip | Store submission/manual distribution | | `--zip-filename` | Sets custom zip name | CI naming conventions | | `--zip-dir` | Sets the folder for the ZIP files | A release folder outside `dist` | | `--zip-source` | Adds source archive alongside artifacts | Compliance/review pipelines | Each zip lands in `dist/`, beside the `dist/` folder rather than inside it, because `dist/` is what a store upload or a load-unpacked takes whole. Without `--zip-filename`, the name is the manifest `name` lowercased with every character outside `a-z0-9` and spaces removed, remaining spaces turned into dashes, then the manifest `version` and the browser. A manifest named `My Extension+` at version `1.0.0` packages as `dist/my-extension-1.0.0-chrome.zip`. Because the name is rewritten, read the emitted path from the build output instead of composing it from the manifest name. Under `--output json`, each archive is listed in `zip_artifacts` with its path and size. `--zip-filename` names both archives, and the browser is always appended to the distribution archive, so two browsers built with the same name in separate runs never write over each other. Passing `--zip-filename=review-bundle.zip` with `--zip-source` on a Chrome build writes `dist/review-bundle-chrome.zip` and `dist/review-bundle-source.zip`. The source archive is the same for every browser, so its name carries none, and one build writes one source archive. A name that already ends in the browser is left alone. Building `--browser=edge,chrome --zip-filename=my-extension.zip` writes `dist/my-extension-edge.zip` and `dist/my-extension-chrome.zip`. From the release after 4.1.39, `--zip-dir ` chooses the folder that the ZIP files go to. The path is relative to the project root, or absolute. `--zip-dir release` writes `release/my-extension-1.0.0-chrome.zip`, and the source archive lands in the same folder. The same setting goes in `extension.config.js` as `commands.build.zipDir`. The build stops with an error for two paths. One is a relative path that leaves the project, such as `../release`. Pass an absolute path to write outside the project. The other is a folder inside `dist/`, because that folder ships whole. `--zip-filename` sets the name only. A folder in its value is dropped, so `--zip-filename=out/review.zip` on a Chrome build names the file `review-chrome.zip`. ## Source maps for a production build A production build writes no source maps. From the release after 4.1.39, `--source-maps` writes a `.map` file beside each script and stylesheet in `dist/`: ```bash theme={null} npx extension@latest build --source-maps --zip ``` The maps never go in the ZIP file. They stay in `dist/` for you, so you can read a stack trace from the build that you shipped. Set `commands.build.sourceMaps: true` in `extension.config.js` to write them on every build. The default is `false`. ## Examples ### Building with zip output and custom filename [Extension.js: extension build for Edge and Chrome](https://www.youtube-nocookie.com/embed/zgJBCat97Sc?rel=0) ```bash npm theme={null} npx extension@latest build ./my-extension --browser=edge,chrome --zip --zip-filename=my-extension.zip ``` ```bash pnpm theme={null} pnpx extension@latest build ./my-extension --browser=edge,chrome --zip --zip-filename=my-extension.zip ``` ```bash yarn theme={null} yarn dlx extension@latest build ./my-extension --browser=edge,chrome --zip --zip-filename=my-extension.zip ``` ```bash bun theme={null} bunx extension@latest build ./my-extension --browser=edge,chrome --zip --zip-filename=my-extension.zip ``` ```bash deno theme={null} deno run -A npm:extension@latest build ./my-extension --browser=edge,chrome --zip --zip-filename=my-extension.zip ``` In this example, the build targets Edge and Chrome and zips both outputs. The archives are saved as `dist/my-extension-edge.zip` and `dist/my-extension-chrome.zip`, because the browser is appended to every distribution archive, even when you build one target. ### Building with polyfill support ```bash npm theme={null} npx extension@latest build ./my-extension --browser=chrome,firefox --polyfill ``` ```bash pnpm theme={null} pnpx extension@latest build ./my-extension --browser=chrome,firefox --polyfill ``` ```bash yarn theme={null} yarn dlx extension@latest build ./my-extension --browser=chrome,firefox --polyfill ``` ```bash bun theme={null} bunx extension@latest build ./my-extension --browser=chrome,firefox --polyfill ``` ```bash deno theme={null} deno run -A npm:extension@latest build ./my-extension --browser=chrome,firefox --polyfill ``` In this example, the build targets Chrome and Firefox and includes polyfill support where relevant. ### Building source and artifact zip ```bash npm theme={null} npx extension@latest build ./my-extension --zip --zip-source ``` ```bash pnpm theme={null} pnpx extension@latest build ./my-extension --zip --zip-source ``` ```bash yarn theme={null} yarn dlx extension@latest build ./my-extension --zip --zip-source ``` ```bash bun theme={null} bunx extension@latest build ./my-extension --zip --zip-source ``` ```bash deno theme={null} deno run -A npm:extension@latest build ./my-extension --zip --zip-source ``` ## What a successful build prints After the asset summary, a successful build prints the output directory and its size, then a link you can use to share the build for review: ```plaintext theme={null} ⏵⏵⏵ Extension built for production in dist/chrome (35.5 KB). ⏵⏵⏵ Send this build to someone for review: https://docs.extension.dev/share/unpublished-build-for-review ``` Each target prints its own pair of lines, so a multi-browser build repeats them once per browser. From the release after 4.1.39, the size in that line counts the files that ship. Source maps are counted apart, and the line says how much was left out of the ZIP file: ```plaintext theme={null} ⏵⏵⏵ Extension built for production in dist/chrome (35.5 KB, plus 112.4 KB of source maps left out of the zip). ``` Builds that succeed with warnings print the warning details above those lines, and the compile line reads `compiled with warnings` instead of `compiled in`. From the release after 4.1.39, a warning or an error from a file that several entries import prints once and counts once. Bundler errors and warnings also print as plain text when the output is not a terminal or `NO_COLOR` is set, in `build` and in `dev`. `FORCE_COLOR=1` keeps the color, and `FORCE_COLOR=0` turns it off. Do not gate CI on this prose. It is written for people and it changes between releases. Use the exit code, or `--output json` below, which is the supported machine contract. ## Machine output with `--output json` `--output json` prints one schema-1 envelope on stdout and routes the human build lines to stderr. Stdout stays parseable as a single JSON document. * A successful run prints a `status: "built"` frame. Its `value` carries the built browsers, the resolved mode, and one summary per browser. Each summary records the output path, asset totals, warning text, and the Safari app identity when relevant. Each warning string opens with `E_CODE: ` when a code resolves, for example `E_CSS_DEAD_REF: ...`, the same convention `logs` and `uninstall` use. * A failed build prints one `ok: false` frame with `status: "build-failed"` before the process exits `1`. A compile error carries `error.code: "E_COMPILE"`, and `error.details` lists each diagnostic behind it with its own code, file, and position, errors first, capped at 20 with `truncated: true` when cut. See [Compile diagnostics](/docs/contracts/result-envelope). A missing project folder carries `E_PROJECT_NOT_FOUND`, a folder with no manifest carries `E_MANIFEST_NOT_FOUND`, and a manifest that does not parse carries `E_MANIFEST_INVALID`. A config file that fails to load carries `E_CONFIG_LOAD`. * When the path argument is a remote URL, the download progress lines go to stderr as well. A reply that is not a ZIP archive, a damaged one, or one with an entry outside its folder carries `E_REMOTE_ZIP_INVALID`, a timeout carries `E_REMOTE_FETCH_TIMEOUT`, a 401 or 403 carries `E_REMOTE_ACCESS_DENIED`, and a refused connection or any other HTTP error carries `E_REMOTE_DOWNLOAD`. An archive with an entry outside its folder is refused before anything is written, and its message names that entry. Every build also writes `dist/extension-js//build-summary.json`. Scripts that shell out to `extension build` can read structured warnings there. Guard against stale files by checking the file's modification time. From the release after 4.1.39, `total_assets`, `total_bytes` and `largest_asset_bytes` in each summary count the files that ship. A build that wrote source maps reports them apart as `source_map_assets` and `source_map_bytes`. A build that wrote none omits both fields. ## Store check for Firefox builds From 4.1.18, a production build for a Gecko target (`firefox`, `gecko-based`, and the Gecko forks) runs [addons-linter](https://github.com/mozilla/addons-linter) over `dist/` when that package is installed in your project. The linter is what addons.mozilla.org runs on a submission, so the check surfaces a rejection before you upload. Every finding prints as a warning. The build never fails because of one, and the exit code stays `0`. A summary line comes first, then one line per finding with the linter's code, message, and location: ```plaintext theme={null} Store check for addons.mozilla.org: addons-linter found 1 error and 2 warnings in dist/firefox AMO : (:) ``` The output is capped at 20 findings, and the linter gets 10 seconds. Past 20, one line names how many more there are and points at `npx addons-linter dist/firefox` for the full report. A linter that runs past 10 seconds is dropped, and the build goes on without the check. A finding in a chunk that bundles a dependency is attributed, because the file name alone can point at the wrong author. The line ends with `- this file is bundled dependency code (react, react-dom), not yours` when nothing of yours is in that chunk, or `- this file also bundles react, react-dom, so the finding may be theirs` when the chunk mixes both. When addons-linter is not installed, the build prints one info line per project and skips the check: ```plaintext theme={null} Skipped the addons.mozilla.org lint: addons-linter is not installed. Install it with: npm install -D addons-linter or pass --no-addon-lint to silence this. ``` The install command is phrased for the package manager that your project uses. Turn the check off with `--no-addon-lint`, or with `commands.build.addonLint: false` in `extension.config.js`. Non-production modes skip it, because a dev artifact carries dev-only grants that the linter would flag for nothing. `extension start` skips it too, since `start` previews a build rather than shipping one. ## Firefox builds split large files addons.mozilla.org does not parse a script of 5 MB or more, and the store check fails on one. From the release after 4.1.39, a build for a Gecko target caps the files it can split at 4 MB of source. Chrome, Edge and Safari output is unchanged. | Code | What ships | | - | - | | Code that two or more pages share | `shared/commons.js` under the cap. Past it, numbered files such as `shared/commons-0.js` and `shared/commons-1.js`. | | A page's own code | `action/index.js` under the cap. Past it, `action/index-0.js` and `action/index-1.js`, so there may be no `action/index.js`. | | A chunk loaded with dynamic `import()` | Parts under the cap, on a page, a background script and a content script alike. | | A background script, content script or injected script | One file at any size. The browser loads each as a single file, so the build cannot split it. | The page lists each part in its HTML, so a split page needs no change from you. Do not name `action/index.js` or `shared/commons.js` in your own code for a Firefox build. For a single-file script past the limit, the store check reports `FILE_TOO_LARGE`, and the line ends with the fix: load the large dependency with a dynamic `import()` so that it ships as its own file under the limit. When addons-linter is not installed, does not answer, or is turned off with `--no-addon-lint` or `commands.build.addonLint: false`, the build prints the same fix on a line that starts with `Firefox build:`. A file is never reported on both lines: ```plaintext theme={null} Firefox build: background/scripts.js is 6.2 MB - addons.mozilla.org does not parse a file of 5 MB or more, and Firefox loads a background script as one file, so the build cannot split it: load a large dependency with a dynamic import() so it ships as its own file under the limit, or remove it ``` The cap is part of the default `optimization.splitChunks` for Gecko targets. Change it from the `config` hook, see [Rspack configuration](/docs/features/rspack-configuration#share-a-module-between-entries). ## Readable output for Opera Add-ons Opera's [acceptance criteria](https://help.opera.com/en/extensions/acceptance-criteria/) require code the reviewers can read: an extension whose own code is minified or obfuscated is rejected, while third-party libraries may stay minified. So `extension build --browser=opera` in production mode does not minify, and prints one info line: ```plaintext theme={null} Opera Add-ons reviews readable source, so this build does not minify first-party code. Pass --minify to minify it anyway. ``` The build turns minification off for the whole bundle, dependencies included, because a bundled chunk can mix your code with theirs. Pass `--minify` to override it, or set `commands.build.minify` in `extension.config.js`. The same option works the other way for every other target: `--no-minify` keeps a Chrome or Firefox build readable when a reviewer asks for it. ## Best practices * **Check build logs:** Review logs for warnings and missing assets after each build. * **Optimize your manifest:** Keep `manifest.json` compatible with every target browser. * **Name artifacts intentionally:** Use `--zip-filename` for stable CI artifact naming. * **Validate target output:** Check each `dist/` folder before publishing. A later `dev` session overwrites that same folder with a dev-instrumented build that adds permissions such as `scripting`, `tabs`, `management`, and `storage`, unions the match patterns of your content scripts into `host_permissions`, and lists `hot/*` and `extension-js-control.json` as web-accessible resources for those same matches. A project with no content scripts gets neither of the last two. Run `build` again before you package or publish. ## Next steps * Send the build to a reviewer behind a link by following [Share an unpublished build for review](https://docs.extension.dev/share/unpublished-build-for-review?utm_source=extension-js-org\&utm_medium=sponsor\&utm_campaign=docs-seam). * Submit the artifacts to the browser stores by following [the extension.dev publish docs](https://docs.extension.dev/publish/overview?utm_source=extension-js-org\&utm_medium=sponsor\&utm_campaign=docs-seam). * Get a shareable URL for a project on extension.dev with [`publish`](/docs/commands/publish). * Run existing build output with [`preview`](/docs/commands/preview). * Build and launch in one command with [`start`](/docs/commands/start). * Configure shared defaults in [`extension.config.js`](/docs/features/extension-configuration). * Review configuration env loading behavior in [Environment variables](/docs/features/environment-variables#how-it-works). * Review supported targets in [Browsers available](/docs/browsers/browsers-available). # Capabilities command for engine handshakes Source: https://extension.js.org/docs/commands/capabilities Print the Extension.js engine version, contract schema versions, and json-capable commands in one machine-readable handshake for scripts and agents. Print the engine version, contract versions, and json-capable commands. `capabilities` is the handshake an agent or script runs before anything else. One call tells the caller which CLI it is talking to, which contract schemas that CLI writes, and which commands accept `--output json`. It needs no project, no session, and no browser. ## When to use `capabilities` * An agent starts a session and must know which schema versions to parse. * A script wants to feature-detect `--output json` support instead of guessing by version. * You want to confirm which CLI build a `npx` invocation actually resolved. ## Usage ```bash npm theme={null} extension capabilities [options] ``` ```bash pnpm theme={null} extension capabilities [options] ``` ```bash yarn theme={null} extension capabilities [options] ``` ```bash bun theme={null} extension capabilities [options] ``` ```bash deno theme={null} extension capabilities [options] ``` ## Arguments and flags | Flag | What it does | Default | | - | - | - | | `--output ` | Result format. | `json` | This is the only command that defaults to `json`. A handshake exists for machines, so the machine format is the default and `--output pretty` is the opt-in. ## What it returns The JSON output is a schema-1 envelope (see [Result envelope](/docs/contracts/result-envelope)) whose `value` carries six fields: ```json theme={null} { "schema": 1, "ok": true, "command": "capabilities", "status": "ok", "value": { "name": "extension", "version": "4.0.22", "envelopeSchema": 1, "readySchemaVersion": 2, "outputJsonCommands": ["build", "capabilities", "dev", "doctor", "eval", "..."], "recordStreamCommands": ["logs"] }, "error": null, "warnings": [] } ``` | Field | What it tells you | | - | - | | `name` | The CLI package name. | | `version` | The CLI version that answered. | | `envelopeSchema` | The result envelope schema this CLI writes. | | `readySchemaVersion` | The `ready.json` contract version this CLI's bundled engine writes. | | `outputJsonCommands` | Every command that accepts `--output json`, sorted. `logs` is in this list. | | `recordStreamCommands` | The subset whose `--output json` success path streams one record per line instead of one envelope. | `outputJsonCommands` and `recordStreamCommands` are read off the live command registrations, never a hand-kept list, so they cannot drift from what the CLI actually accepts. Treat the example above as illustrative and parse the real answer. A reader that expects one envelope on stdout must skip the commands in `recordStreamCommands`, which print log records on success and an envelope only on failure. Pretty output prints the same facts as five labeled lines. Both formats exit with code `0`. ## Typical agent flow 1. Run `extension capabilities` and check `envelopeSchema` and `readySchemaVersion` are versions that you support. 2. Start the session: `extension dev --allow-control --output json`. 3. Drive it with the act verbs: [`inspect`](/docs/commands/inspect), [`eval`](/docs/commands/eval), [`storage`](/docs/commands/storage), [`reload`](/docs/commands/reload). ## Next steps * Read the envelope that every json-capable command emits in [Result envelope](/docs/contracts/result-envelope). * Start the session that the handshake prepares for with [`dev`](/docs/commands/dev). * Read the wider debugging workflow in [Debugging](/docs/debugging). # Create command to scaffold extension projects Source: https://extension.js.org/docs/commands/create Scaffold a new browser extension project from an official template with one CLI command. Choose React, Vue, Svelte, TypeScript, or vanilla JS. `create` scaffolds files, configuration, and starter scripts for the selected template and optionally installs dependencies. For a file-by-file tour of the generated tree, see [What create generates](/docs/getting-started/create-your-first-extension#what-create-generates). ## When to use `create` * Start a new extension from scratch. * Spin up multiple proof-of-concept ideas quickly. * Standardize onboarding for your teammates with consistent template defaults. ## Create command capabilities | Capability | What it gives you | | - | - | | Template scaffolding | Start with official templates and a ready project structure | | Dependency install | Optionally install required packages after scaffold | | Path flexibility | Create by project name or explicit folder path | | Fast onboarding | Move from empty folder to runnable extension quickly | ## Usage > [!NOTE] > > **Using Yarn?** The `yarn dlx` command requires Yarn 2 or later. Yarn 1 does > not include `dlx` and fails with a "Command not found" error. On Yarn 1, use > the `npm` tab (`npx`) instead. ```bash npm theme={null} npx extension@latest create [options] ``` ```bash pnpm theme={null} pnpx extension@latest create [options] ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create [options] ``` ```bash bun theme={null} bunx extension@latest create [options] ``` ```bash deno theme={null} deno run -A npm:extension@latest create [options] ``` ## Arguments and flags | Flag | Alias | What it does | Default | | - | - | - | - | | `[path or name]` | - | Project folder/name to create. | required | | `--template ` | `-t` | Catalog name, GitHub URL, or ZIP URL to scaffold from. | `typescript` | | `--install [boolean]` | - | Installs dependencies after scaffolding. | `false` | | `--source ` | - | Attribution tag for where this create started (for example `cli`). Recorded in anonymous telemetry only. | unset | | `--output ` | - | Result format. `json` prints a schema-1 envelope on stdout. | `pretty` | When you want the default TypeScript starter, omit `--template` entirely. Add `--template=` only for another stack from the [official examples](https://github.com/extension-js/templates/tree/main/examples). `--template` also accepts a GitHub URL or a ZIP URL, so you can scaffold from any repository. From 4.1.19, a template URL must use `https://`. `create` refuses a plain `http://` URL, and a download that redirects to `http://`, before it writes the project. To allow `http://` on a network that you trust, set `EXTENSION_ALLOW_HTTP_TEMPLATE=true`. The catalog holds 60 templates in 7 groups: starters, sidebar, content scripts, new tab, toolbar action, DevTools panel, and special folders. Run `extension create --help` for the full list. The default `typescript` template downloads the catalog archive like every other name. Only the `javascript` template ships inside the CLI. When you omit `--template`, `EXTENSION_CREATE_TEMPLATE_URL` is not set, and the download fails, `create` falls back to that bundled `javascript` template and says so, naming the network error, so an offline machine still gets a project. An explicit `--template` that fails to download fails loudly instead. A scaffold has one package manager. A starter's `packageManager` pin (or a `pnpm-workspace.yaml` it ships) decides it, otherwise the manager that invoked `create` does. The `packageManager` field written to `package.json`, the `--install` run, and the printed next steps all name that same manager. ## Template corpus pinning Catalog downloads are pinned to one immutable commit of the templates repository. Two scaffolds of the same version therefore produce the same bytes. Two environment variables override the pin: * `EXTENSION_CREATE_TEMPLATE_REF` points at another ref. Set it to `main` to restore floating behavior. * `EXTENSION_CREATE_TEMPLATE_URL` points at another archive URL entirely. When it is set and that archive cannot be used, `create` fails and never falls back to the bundled template. Each scaffold writes a `.extension-create.json` provenance file into the project. It records the create version, the template, and the source, plus the resolved ref when the template came from the catalog archive, so template drift stays auditable. The bundled `javascript` starter records `"source": "bundled"` and no ref. Every template also carries a `.mcp.json` file that MCP clients read. When the folder already has a `.mcp.json`, `create` keeps it as it is. From the release after 4.1.39, a `create` that fails partway in an existing folder puts your `.gitignore` and `.mcp.json` back as they were. ## Machine output with `--output json` `--output json` prints one schema-1 envelope on stdout and routes scaffold progress lines to stderr: * A successful run prints a `status: "created"` frame. Its `value` carries `projectPath`, `projectName`, `template`, and `depsInstalled`. * Failures print `ok: false` with an `error.code`: `E_TEMPLATE_NOT_FOUND` for an unknown catalog name, `E_NETWORK` for a failed download (a refused connection, an HTTP error, or a timeout), `E_DESTINATION_NOT_EMPTY` or `E_DESTINATION_NOT_WRITABLE` for destination problems. * A template URL that answers with something other than a ZIP archive, or with a damaged one, fails with `E_REMOTE_ZIP_INVALID` and leaves nothing on disk. * An archive with an entry outside its folder fails with `E_REMOTE_ZIP_INVALID` too, from a template URL or from `EXTENSION_CREATE_TEMPLATE_URL`. `create` checks every entry before it writes one, so the message says the archive was refused, names the entry, and gives no advice to try again. * `EXTENSION_CREATE_TIMEOUT_MS` bounds the whole template fetch, retry included. A fetch that runs out of time fails with `E_NETWORK` and the reason `No answer within N seconds`. * An `EXTENSION_CREATE_TEMPLATE_URL` that fails never falls back to the bundled `javascript` template. A page or a damaged archive fails with `E_REMOTE_ZIP_INVALID`, and a refused connection, an HTTP error, or a timeout fails with `E_NETWORK`. The message names the variable, and nothing is left on disk. * A plain `http://` template URL without `EXTENSION_ALLOW_HTTP_TEMPLATE=true` fails with `E_INVALID_OPTION`. ## Shared global options Also supports [Global flags](/docs/workflows/global-flags). ## Example commands ```bash npm theme={null} npx extension@latest create my-extension --template=newtab-react ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=newtab-react ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=newtab-react ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=newtab-react ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=newtab-react ``` [Extension.js: npx extension create scaffolds a project](https://www.youtube-nocookie.com/embed/9Bm-PAQdQks?rel=0) ```bash npm theme={null} npx extension@latest create my-extension --install ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --install ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --install ``` ```bash bun theme={null} bunx extension@latest create my-extension --install ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --install ``` ## Available templates > [!TIP] > > For the full, continuously updated list of templates, browse the [examples > repository](https://github.com/extension-js/templates/tree/main/examples). > [card] [JavaScript](https://github.com/extension-js/templates/tree/main/examples/javascript) > > Minimal bundled starter. Use when you want a clean baseline or are offline. > [card] [TypeScript (default)](https://github.com/extension-js/templates/tree/main/examples/typescript) > > Typed sidebar starter with `tsconfig.json` preconfigured. > [card] [React](https://github.com/extension-js/templates/tree/main/examples/newtab-react) > > React UI wired for content scripts and popup views. > [card] [Vue](https://github.com/extension-js/templates/tree/main/examples/newtab-vue) > > Vue UI with single-file component (SFC) support baked in. ## Best practices * Start from a template that matches your UI/runtime needs to reduce setup drift. * Keep the first run small, then add extra tooling after verifying baseline command flow. # Dev command for watch mode and live reload Source: https://extension.js.org/docs/commands/dev Develop browser extensions with watch mode, hot module replacement, automatic browser launch, and context-aware reload via the Extension.js dev command. Use `dev` for day-to-day browser extension development with watch mode, browser launch, and context-aware update behavior. `dev` runs the development pipeline and watches your project files. It applies update strategies based on what changed: hot module replacement (HMR), hard reload, or a full restart when the change requires it. [Extension.js: edit the manifest, dev restarts the extension](https://www.youtube-nocookie.com/embed/B1yvJ5AcTwo?rel=0) ## When to use `dev` * Building features and validating changes in real time. * Debugging extension behavior in one or more browser targets. Use `build` for production artifacts, `start` for production build + launch, and `preview` to run existing build output only. If your extension lives inside a monorepo/submodule, review how `extension.config.*` loads env files (including workspace-root fallback): [Environment variables](/docs/features/environment-variables#how-it-works). ## Dev command capabilities | Capability | What it gives you | | - | - | | Watch mode iteration | Tight edit → rebuild → validate loop while coding | | Browser-target control | Explicit cross-browser validation per command | | Profile-aware runs | Reliable fresh or persisted profiles by workflow need | ### What triggers a rebuild The watcher follows the build graph: the manifest and everything it names, each entry and its imports, the `pages/`, `scripts/` and `public/` folders, `_locales/`, and the project config and env files. A write anywhere else in the project, such as a screenshot under `store/`, a demo page, a README or a test fixture, never rebuilds or reloads the extension. A special folder created while `dev` runs is picked up on the next compile. From the release after 4.1.39, a project under a symlinked folder is watched by one path. On macOS, the first build waits a bounded time for the watcher's first scan before it reports ready. An early save is then not missed. ## Usage ```bash npm theme={null} extension dev [path-or-url] [options] ``` ```bash pnpm theme={null} extension dev [path-or-url] [options] ``` ```bash yarn theme={null} extension dev [path-or-url] [options] ``` ```bash bun theme={null} extension dev [path-or-url] [options] ``` ```bash deno theme={null} extension dev [path-or-url] [options] ``` > [!NOTE] > > The CLI is not installed globally. `npx extension@latest dev` downloads the > current release and runs it, so `extension` alone is not a command in your > shell. Inside a project that `create` made, `npm run dev` runs the same > command through the `dev` script in `package.json`. If you omit the path, Extension.js uses the current working folder. You can also pass a **GitHub tree URL** (for example, `https://github.com/user/repo/tree/main/path`). Extension.js downloads the repository and runs development mode on the local copy. ## Most-used flags These cover the 80% case. Skip to the [full reference](#arguments-and-flags) for the rest. | Flag | What it does | Default | | - | - | - | | `--browser ` | Target Chrome, Edge, Firefox, or comma-separated list. | `chromium` | | `--polyfill` | Bridge `browser.*` API to Chromium targets for Firefox-flavored sources. | `true` | | `--port ` | Dev server port. Use `0` for OS-assigned. | `8080` | | `--starting-url ` | Open this URL when the browser launches. | unset | | `--no-reload` | Skip auto-reload. Use when you want a clean dev bundle. | reload on | ## Arguments and flags | Flag | Alias | What it does | Default | | - | - | - | - | | `[path or url]` | - | Extension path or remote URL. | `process.cwd()` | | `--browser ` | `-b` | Browser/engine target (`chromium`, `chrome`, `edge`, `firefox`, named forks like `brave`/`waterfox`, engine aliases, or comma-separated values). | `chromium` | | `--profile ` | - | Browser profile path or boolean profile mode. | fresh profile | | `--chromium-binary ` | - | [Custom Chromium-family binary path](/docs/browsers/running-other-browsers). | managed install, then system install | | `--gecko-binary ` | `--firefox-binary` | [Custom Gecko-family binary path](/docs/browsers/running-other-browsers). | managed install, then system install | | `--polyfill [boolean]` | - | Enable `browser.*` API compatibility polyfill for Chromium targets. | `true` | | `--no-polyfill` | - | Disable the cross-browser polyfill. | polyfill enabled | | `--starting-url ` | - | Starting URL in launched browser. | unset | | `--port ` | - | Requested dev server port. Use `0` for an OS-assigned port. See [how the port resolves](#how-the-port-resolves). | `8080` | | `--host ` | - | Host to bind the dev server to. Use `0.0.0.0` for Docker/dev containers. | `127.0.0.1` | | `--public-host ` | - | Connectable host the browser dials for HMR and the reload bridge, when it differs from the bind `--host` (remote/dev container). | bind host (`127.0.0.1` when bound to `0.0.0.0`) | | `--allowed-hosts ` | - | Comma-separated host names the dev server answers besides localhost, IP addresses and `--public-host` (docker service names, tunnels, `*.local`). A leading dot allows every subdomain. Also `commands.dev.allowedHosts` in `extension.config.js`. See [bind host vs. connectable host](#bind-host-vs-connectable-host). | none | | `--no-open` | - | Launch the browser, but do not open a tab for your extension. The browser still starts and loads it. See [stop the browser from launching](#stop-the-browser-from-launching). | a tab opens on launch | | `--no-browser` | - | Stop the browser from launching. The dev server still starts and keeps rebuilding. See [stop the browser from launching](#stop-the-browser-from-launching). | browser launch enabled | | `--no-reload` | - | Skip the content-script reload runtime and on-rebuild reload dispatch. Reload tabs manually to see changes. | reload runtime enabled | | `--wait [boolean]` | - | Wait for `dist/extension-js//ready.json` and exit. Requires a local project path. | disabled | | `--wait-timeout ` | - | Timeout for `--wait` mode. | `60000` | | `--output ` | - | Result format. `json` prints a schema-1 envelope on stdout. | `pretty` | | `--extensions ` | - | Comma-separated companion extensions or store URLs. | unset | | `--install [boolean]` | - | Internal flag. Install project dependencies when missing. Lifecycle scripts stay disabled unless `EXTENSION_ALLOW_INSTALL_SCRIPTS=true`. | command behavior default | | `--allow-control` | - | Enable the agent-bridge control channel for the act verbs (`inspect`, `reload`, `storage`, `open`, `navigate`). | disabled | | `--allow-eval` | - | Also enable `extension eval`. Implies `--allow-control` and writes a `0600` session token. | disabled | | `--enable-extension` | - | Turn the extension on in Safari Settings and allow it on other websites through macOS Accessibility, after a one-time grant for your terminal app. The run asks for its WebDriver session first, so quit Safari before you start. Safari can ask for Touch ID or your password. Safari targets only. | off | | `--parent-pid ` | - | Exit the dev server as soon as the given process ID dies. See [parent watchdog](#parent-watchdog). | unset | | `--debug` | - | Enable maintainer diagnostics. | disabled | On Firefox, `--starting-url` opens after the add-on installs, so your `document_start` content scripts run on that page. From the release after 4.1.39, it no longer replaces a tab that your extension opened. Two deprecated aliases are hidden from `--help` but still work: * `--wait-format ` maps onto `--output` and warns once on stderr. Migrate scripts to `--output`. * `--author` and `--author-mode` map onto `--debug`. ### Safari flags These flags apply to `safari` and `webkit-based` targets only. Passing any of them with another target exits with `E_INVALID_OPTION`, so a typo never no-ops silently. | Flag | What it does | Default | | - | - | - | | `--safari-binary ` | Safari binary to open after packaging. | system Safari | | `--app-name ` | Override the Safari app name. | the manifest `name` | | `--bundle-id ` | User-owned bundle identifier in reverse-DNS form. A malformed value fails before any build. | a generated `dev.extensionjs.*` id | | `--app-icon ` | Build the Safari app icon from this square PNG, ideally 1024 px, used as is. Without it, the icon is the manifest icon on a white plate, so a tile-shaped icon ends up as a tile inside a tile. | the plated manifest icon | | `--macos-only [boolean]` | Generate a macOS-only Xcode project. Pass `false` for a universal macOS + iOS project. | `true` | | `--force-regenerate` | Regenerate the Safari Xcode project even when up to date. | disabled | For Safari targets, `dev` also runs a toolchain preflight before the first bundle. A missing Xcode fails fast with `E_SAFARI_TOOLCHAIN`. From 4.1.20, a Safari session is a full dev session. Once you enable the extension in Safari Settings, `extension logs` reads it, the control bridge attaches, and every save reloads the extension in Safari. See [Building Safari extensions](/docs/browsers/safari). ### Emulated Chromium From 4.1.38, `--browser=chromium-emulator` runs your extension in an emulated Chromium inside a web page, with no flag or environment variable to set. `dev` prints the page address and opens it in your default browser. The page reads your build from the dev server on your machine, so only `dev` opens this target. `start` and `preview` refuse it. Before it opens the page, `dev` checks that the engine origin answers. When the origin does not answer, `dev` prints one warning and opens nothing: ```text theme={null} the emulated Chromium origin https://browsers.extension.land did not answer, so there is no page to open. Check your connection, then run extension dev again, or run this project with --browser=chrome. ``` The dev server keeps running. `--logs` has no effect on this target: the extension runs in a web page, so read its console in your browser's devtools on that page. ### Parent watchdog `--parent-pid` is for harnesses and agents that spawn `dev`, so a crashed owner cannot leak a server. The value must be a positive integer, anything else exits with `E_INVALID_OPTION`. The watchdog polls the parent process every 2 seconds. When the parent is gone, the dev server shuts down via `SIGTERM`, with a 5 second hard-exit backstop if cleanup wedges. ### How the port resolves `--port` is a request, not a guarantee. When the requested port is busy, the dev server walks upward to the nearest free port. `--port 0` asks the OS for any free port. Read the bound port from `ready.json`, not from the flag you passed. `--port` sets the dev server port only. The control bridge listens on its own port, and no flag sets it. On the first run, the session asks the OS for a free port and stores it in `.extension-js/control-port-`. The next run asks for the same port, so a browser profile that still holds the old one can reconnect. When that port is busy, the OS assigns another. Read it from `controlPort` in `ready.json`. ### What `dev` adds to your extension A dev session grants itself what the reload needs, and the production build of the same source has none of it. From the release after 4.1.39, the session names each addition under the identity card: ```text theme={null} Dev only permissions scripting, tabs Dev only host access https://example.com/* Dev only web_accessible_resources hot/*, extension-js-control.json Dev flag --silent-debugger-extension-api hides the debugger bar, excludeBrowserFlags shows it ``` * A `Dev only` line lists the permissions, host access, or web accessible resources that only the dev manifest has. * A `Dev flag` line names a launch flag that changes what you see, and the config key that flips it. * A `Dev pref` line names a browser preference that the session wrote to a profile that outlives it. See [Browser preferences](/docs/browsers/browser-preferences#the-startup-preference-on-a-kept-profile). `ready.json` lists every entry with its reason under [`devAdditions`](/docs/contracts/ready-json#dev-additions). Nothing on these lines ships. Run `extension build` and read `dist//manifest.json` to see what a store receives. ### The first page waits for boot registrations A background script can register content scripts as it starts, with `scripting.registerContentScripts`. A page that loads before that call answers never runs the registered script. From the release after 4.1.39, `dev` holds the first page until the background finishes its startup work. That covers a registration made after awaited calls, such as a `fetch` or a storage read. The wait is bounded at about five seconds, so the page always opens. A registration behind a timer is not waited for. `dev` cannot tell when a `setTimeout` callback or an alarm will fire. The CLI can print two lines. The first one prints when the wait runs out: ```text theme={null} Opened https://example.com/ before the background finished registering content scripts (waited 5s). Reload the page if a registered script did not run on it. ``` The second one prints when a registration arrives after the page opened: ```text theme={null} The background registered a content script 6.2s after it started, when the first page was already open. If the script did not run on that page, reload it. ``` In both cases, reload the page if the script did not run on it. A registered script runs only on pages that load after the registration. Firefox can still run the script on a page it was already opening, so check before you reload. `start` and `preview` hold the first page the same way, for a registration made as the background starts or after a storage read. They do not wait for a registration behind an awaited `fetch` or a timer. For those, they print the second line when the registration arrives in the first 15 seconds. ## Automation metadata (recommended for scripts/agents) When `dev` runs, Extension.js emits machine-readable metadata under: * `dist/extension-js//ready.json` * `dist/extension-js//events.ndjson` (newline-delimited JSON) For automation (Playwright, continuous integration (CI), AI agents), prefer these files over terminal log parsing. Treat `ready.json` as the readiness contract: * `status: "starting"` while booting * `status: "ready"` when the build compiled. From the release after 4.1.39, with `--allow-control` or `--allow-eval` and a launched browser, `ready` also waits up to 10 seconds for the background to connect * `status: "error"` for startup/compile failures, and for a browser that never started (`code: "browser_launch_failed"`) or exited before the extension loaded (`code: "browser_exited"`) * `status: "stopped"` after the session shut down, so a dead session never advertises `ready` * `runtime: "attached"` (with `executorAttachedAt`) once the service worker connected. Act verbs should wait for this, not for `ready` * `runtime: "detached"` (with `executorDetachedAt`) from 4.1.20, once the last connected extension context disconnects. `executorAttachedAt` stays as provenance, and the value goes back to `"attached"` on reconnect * `runId` uniquely identifies a runtime session * `startedAt` marks the runtime session start timestamp * `command` names the producing command (`dev`, `start`, `preview`, or `build`) * `toolchainVersion`, `extensionName`, and `extensionVersion` record which Extension.js version produced the tree, for which extension. The file doubles as a build receipt after the terminal scrollback is gone * `port` is the bound dev server port, and `host` is the connectable host clients dial (see [bind host vs. connectable host](#bind-host-vs-connectable-host)) * `controlPort` / `instanceId` locate the control bridge used by `extension logs` and the act verbs * `cdpPort` (Chromium) and `rdpPort` (Gecko) expose the browser debugging ports * `profilePath`, `browserPid`, and `extensionId` are stamped by the browser launcher after launch The full schema, error states, and two-phase readiness rules live in [the ready.json contract](/docs/contracts/ready-json). `events.ndjson` is scoped to the current run: starting a new run resets the file, and every entry is stamped with the run's `runId` (matching `ready.json`), so consumers never see events from a previous session interleaved with the live one. When a session misbehaves, run [`extension doctor`](/docs/commands/doctor): it walks the contract, control channel, token, executor, and browser in order and names the first failing leg with a fix. ### Stop the browser from launching Two flags sound alike and do different things: | You want | Flag | What happens | | - | - | - | | No browser at all | `--no-browser` | No browser process starts. The dev server runs and keeps rebuilding on save. | | A browser, but no tab opened for your extension | `--no-open` | The browser starts and loads your extension. No tab is opened for it. | ```bash theme={null} # Stop the browser launch. The dev server keeps running. npx extension@latest dev --no-browser # Launch the browser without opening a tab for the extension. npx extension@latest dev --no-open ``` `--no-browser` is the run mode for headless, CI, and remote work, and it is the flag the [Playwright end-to-end workflow](/docs/workflows/playwright-e2e) is built on. It also has a config form, `commands.dev.noBrowser: true`, and an environment form, `EXTENSION_CLI_NO_BROWSER=1`. `--no-open` is a launch detail. Reach for it when you want the browser open on whatever it already shows, without Extension.js opening a tab for your extension over it. `dev`, `start`, and `preview` all accept both flags. ### `--no-browser` and readiness synchronization `--no-browser` disables browser launch but keeps the full dev loop. The dev server still watches your files, and on each rebuild it broadcasts a reload over the control bridge to the extension's service worker so your changes apply without a launched browser driving them: * A **content-script** change is re-injected into the already-open matching tabs in place (the service worker runs `chrome.scripting.executeScript` with the fresh build), so the page updates on save without a manual refresh. Tabs opened afterward get the new build too, because the service worker re-registers the content scripts dynamically (`chrome.scripting.registerContentScripts`). * A **service-worker / manifest** change restarts the extension. So `--no-browser` behaves like a normal `dev` session for headless, continuous integration (CI), and remote/dev-container workflows: load the built `dist/` into any browser you control and it keeps updating on save. (Use `--no-reload` for a static dev bundle that never reloads. See below.) `--no-browser` does not block external runners until the compile finishes. For Playwright/CI/AI workflows: 1. Run `extension dev --no-browser` as a long-lived process. 2. Run `extension dev --wait --browser=` as the readiness gate. 3. Launch external browser automation only after `status: "ready"`. `--wait` targets a second process (or CI step) and exits non-zero on `error`/timeout. When `--wait` sees a stale `ready.json` from a dead process (`pid` no longer alive), it keeps waiting for a live producer. `--wait` requires a local project path. Passing a remote URL exits with `E_ARGS`. Passing both `--wait` and `--no-browser` in the same command invocation exits with `E_INVALID_OPTION`, because `--wait` only reads a contract that another process writes. Run them as two processes, as in the steps above. From 4.1.21, a `--wait` that reads `ready.json` while the producer is still writing it treats the half-written file as one more transient state and keeps polling. Up to 4.1.20, one torn read failed the wait with a JSON parse error. A file that never parses still ends in `E_READY_TIMEOUT`, and the timeout message names the cause: `The last read of the file failed to parse as JSON`, followed by the parser's own error. ### Machine output with `--output json` `--output json` prints a schema-1 envelope on stdout: * A plain `dev` run prints one `status: "started"` frame as the first stdout line, once the session exists and right before the `starting` frame. It carries the project path, browser list, requested port, and the dev server `pid`. `dev` never terminates on its own, so no result frame follows. The [lifecycle frames](/docs/contracts/lifecycle-stream) (`starting`, `compiled`, `ready`, and the ones after) follow on stdout, and human progress lines go to stderr, so every stdout line parses as JSON. Read `ready.json` for the live state. * A run refused before the session exists prints one `ok: false` frame and nothing else, with no `started` frame before it. That covers a missing manifest (`E_MANIFEST_NOT_FOUND`), a manifest that does not parse (`E_MANIFEST_INVALID`), a config file that fails to load (`E_CONFIG_LOAD`), and a remote URL that gives no usable archive (`E_REMOTE_ZIP_INVALID`, `E_REMOTE_FETCH_TIMEOUT`, `E_REMOTE_ACCESS_DENIED`, or `E_REMOTE_DOWNLOAD`). * A bad `--chromium-binary` or `--gecko-binary` pin does not stop the server. That covers a path that does not exist, a file that is not executable, and a binary that does not answer its version probe within 10 seconds. The contract goes to `error` with code `browser_launch_failed` and `browserLaunchFailedCode: "E_BROWSER_BINARY_INVALID"`. The failure frame carries that `readyCode` with `status: "usage"` and `error.code: "E_BROWSER_BINARY_INVALID"`, and a `dev --wait` against the session answers with the same status and code. * A pinned binary that is executable but that the system cannot start also keeps the server up. Its failure frame has `status: "failed"`, `error.code: "E_READY_ERROR_STATUS"`, and the `browser_launch_failed` `readyCode`. * A `dev --wait` run prints one `status: "ready"` frame on success. Its `value.results` array carries the full ready contract per browser. * Failures print one `ok: false` frame with an `error.code` (for example `E_READY_TIMEOUT`) before the process exits `1`. A contract in `error` status names its cause: `E_BROWSER_BINARY_INVALID` with `status: "usage"` when the pinned binary was refused, `E_BROWSER_LAUNCH` when the browser never started, `E_BROWSER_EXITED` when it exited before the extension loaded, and `E_COMPILE` for a compile error. See [the ready.json contract](/docs/contracts/ready-json) for the full list. ### `--no-reload` for a clean dev bundle `--no-reload` skips the content-script reinjection wrapper and the on-rebuild reload dispatch. The dev `dist` stays close to a production bundle and an open tab is not disturbed when files change. Reload the extension or page yourself to pick up changes. `--no-reload` is only supported on `extension dev`. Passing it to `start`, `preview`, or `build` exits with an error. Internally it sets `EXTENSION_NO_RELOAD=true` so the develop process can read it from outside the CLI argv. Dev builds emit `cheap-module-source-map` files that describe your source: the original TypeScript and the exact lines, for content scripts, classic multi-file groups, the background, and pages on both manifest versions. No `eval` variant is used, so the bundle runs under your own CSP. ## Logging flags These flags are experimental and may change between minor releases. | Flag | What it does | Default | | - | - | - | | `--logs ` | Minimum log level. | `off` | | `--log-context ` | Context filter (`background`, `content`, `page`, `popup`, `options`, `sidebar`, `devtools`, `newtab`, `history`, `bookmarks`). | `all` | | `--log-format ` | Logger output format. | `pretty` | | `--no-log-timestamps` | Disable timestamps in pretty mode. | timestamps enabled | | `--no-log-color` | Disable color in pretty mode. | color enabled | | `--log-url ` | Filter log events by URL substring/regex. | unset | | `--log-tab ` | Filter log events by tab ID. | unset | ## Shared global options Also supports [Global flags](/docs/workflows/global-flags). ## Monorepo and workspace roots You can point `dev` (and `build`) at the **root of a monorepo** instead of the extension package itself. Extension.js detects the workspace root and auto-resolves the extension package inside it: ```bash theme={null} npx extension@latest dev . # run from the monorepo root ``` When exactly one extension package is found, Extension.js resolves it and prints: ```text theme={null} Workspace root detected — resolved extension package: packages/my-extension ``` When several candidates exist, it lists them so you can point at the one you mean: ```bash theme={null} npx extension@latest dev packages/my-extension ``` ### pnpm workspace members install from the root From 4.1.18, when the project is a member of a pnpm workspace and its dependencies are missing, the automatic install runs from the workspace root instead of the package folder. The install is filtered to the member and its workspace dependencies: ```bash theme={null} pnpm install --filter {packages/my-extension}... ``` The lockfile and the linker layout stay the workspace's, so the result matches a `pnpm install` at the root. The session prints one info line before the install runs: ```plaintext theme={null} This project is a pnpm workspace member, installing from the workspace root at /home/dev/monorepo. ``` ## Examples ### Running a local extension [Extension.js: extension dev](https://www.youtube-nocookie.com/embed/ecqoWM0ct1Y?rel=0) ```bash npm theme={null} npx extension@latest dev ./my-extension ``` ```bash pnpm theme={null} pnpx extension@latest dev ./my-extension ``` ```bash yarn theme={null} yarn dlx extension@latest dev ./my-extension ``` ```bash bun theme={null} bunx extension@latest dev ./my-extension ``` ```bash deno theme={null} deno run -A npm:extension@latest dev ./my-extension ``` ### Running a remote extension from GitHub Pass a GitHub tree URL as the argument to develop a remote extension locally: ```bash npm theme={null} npx extension@latest dev https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/functional-samples/sample.page-redder ``` ```bash pnpm theme={null} pnpx extension@latest dev https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/functional-samples/sample.page-redder ``` ```bash yarn theme={null} yarn dlx extension@latest dev https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/functional-samples/sample.page-redder ``` ```bash bun theme={null} bunx extension@latest dev https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/functional-samples/sample.page-redder ``` ```bash deno theme={null} deno run -A npm:extension@latest dev https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/functional-samples/sample.page-redder ``` ### Running in Firefox ```bash npm theme={null} npx extension@latest dev ./my-extension --browser firefox ``` ```bash pnpm theme={null} pnpx extension@latest dev ./my-extension --browser firefox ``` ```bash yarn theme={null} yarn dlx extension@latest dev ./my-extension --browser firefox ``` ```bash bun theme={null} bunx extension@latest dev ./my-extension --browser firefox ``` ```bash deno theme={null} deno run -A npm:extension@latest dev ./my-extension --browser firefox ``` ### Running in multiple browsers in sequence ```bash npm theme={null} npx extension@latest dev ./my-extension --browser=chrome,firefox ``` ```bash pnpm theme={null} pnpx extension@latest dev ./my-extension --browser=chrome,firefox ``` ```bash yarn theme={null} yarn dlx extension@latest dev ./my-extension --browser=chrome,firefox ``` ```bash bun theme={null} bunx extension@latest dev ./my-extension --browser=chrome,firefox ``` ```bash deno theme={null} deno run -A npm:extension@latest dev ./my-extension --browser=chrome,firefox ``` ### Running inside Docker or a dev container When you run inside Docker, dev containers, or GitHub Codespaces, bind the dev server to `0.0.0.0` so the host machine can reach it: ```bash npm theme={null} npx extension@latest dev ./my-extension --host 0.0.0.0 ``` ```bash pnpm theme={null} pnpx extension@latest dev ./my-extension --host 0.0.0.0 ``` ```bash yarn theme={null} yarn dlx extension@latest dev ./my-extension --host 0.0.0.0 ``` ```bash bun theme={null} bunx extension@latest dev ./my-extension --host 0.0.0.0 ``` ```bash deno theme={null} deno run -A npm:extension@latest dev ./my-extension --host 0.0.0.0 ``` Combine with `--port 0` to let the OS choose an available port automatically: ```bash npm theme={null} npx extension@latest dev ./my-extension --host 0.0.0.0 --port 0 ``` ```bash pnpm theme={null} pnpx extension@latest dev ./my-extension --host 0.0.0.0 --port 0 ``` ```bash yarn theme={null} yarn dlx extension@latest dev ./my-extension --host 0.0.0.0 --port 0 ``` ```bash bun theme={null} bunx extension@latest dev ./my-extension --host 0.0.0.0 --port 0 ``` ```bash deno theme={null} deno run -A npm:extension@latest dev ./my-extension --host 0.0.0.0 --port 0 ``` #### Bind host vs. connectable host `--host` is the address the dev server **binds** to. The browser (the HMR client and the reload bridge) needs an address it can actually **connect** to, which is not always the same value: * `--host 0.0.0.0` binds every interface, but `0.0.0.0` is not a connectable address. Extension.js automatically advertises `127.0.0.1` to the browser instead, the right target for the common port-forwarded Docker/dev-container/Codespaces setup, where the browser runs on the host and the port is forwarded to the container. * For a true **remote** setup (the browser runs on a different machine than the dev server), pass `--public-host` with the address the browser can reach (an LAN IP or hostname). It is propagated to the HMR client URL, `ready.json`, and the reload bridge baked into the extension. ```bash npm theme={null} # Browser on another machine reaches the dev server at devbox.local npx extension@latest dev ./my-extension --host 0.0.0.0 --public-host devbox.local ``` ```bash pnpm theme={null} pnpx extension@latest dev ./my-extension --host 0.0.0.0 --public-host devbox.local ``` ```bash yarn theme={null} yarn dlx extension@latest dev ./my-extension --host 0.0.0.0 --public-host devbox.local ``` ```bash bun theme={null} bunx extension@latest dev ./my-extension --host 0.0.0.0 --public-host devbox.local ``` When `--host` is a concrete address already (for example `--host 192.168.1.50`), that value is connectable as-is and is used directly. `--public-host` is only needed when the bind host and the browser-facing host differ. The dev server checks the `Host` header of every request, as a defense against DNS rebinding. It answers `localhost`, IP addresses, the bind host and `--public-host`. A request under any other name gets `403` with a plain-text body that names the refused host and the fix, and the terminal prints one line per refused host. Allow extra names with `--allowed-hosts`, a comma-separated list where a leading dot allows every subdomain, or with `commands.dev.allowedHosts` in `extension.config.js` (an array or a comma string). Use it when the dev server is reached under a docker service name, a tunnel hostname or an mDNS name, without changing what the browser dials. ```bash theme={null} npx extension@latest dev ./my-extension --host 0.0.0.0 --allowed-hosts web,.ngrok.app ``` `--host 0.0.0.0` alone does not allow every name. The bind address and the allowed names are separate settings. ### Running in Brave as a custom binary ```bash npm theme={null} npx extension@latest dev ./my-extension --chromium-binary /path/to/brave ``` ```bash pnpm theme={null} pnpx extension@latest dev ./my-extension --chromium-binary /path/to/brave ``` ```bash yarn theme={null} yarn dlx extension@latest dev ./my-extension --chromium-binary /path/to/brave ``` ```bash bun theme={null} bunx extension@latest dev ./my-extension --chromium-binary /path/to/brave ``` ```bash deno theme={null} deno run -A npm:extension@latest dev ./my-extension --chromium-binary /path/to/brave ``` ## Best practices * **Browser compatibility:** Test your extension in different browsers to verify it works on every target. * **Polyfilling:** The polyfill is on by default in `dev`, so `browser.*` calls work in Chromium-based browsers older than 148 too (152 with a `devtools_page`). Newer versions expose `browser` natively. Pass `--no-polyfill` when you want the raw bundle. * **Automation reliability:** Treat `dev` as the watch-mode companion (`--no-browser` + `dev --wait`). Treat `start` as the production companion (`--no-browser` + `start --wait`). Use `--output=json` for scripts and CI automation. ## Next steps * Build production artifacts with [`build`](/docs/commands/build). * Validate production launch flow with [`start`](/docs/commands/start). * Review browser targeting with [Browser-specific manifest fields](/docs/features/browser-specific-fields). * Configure shared defaults in [`extension.config.js`](/docs/features/extension-configuration). * Review configuration env loading behavior in [Environment variables](/docs/features/environment-variables#how-it-works). # Doctor command for diagnosing dev sessions Source: https://extension.js.org/docs/commands/doctor Diagnose a running Extension.js dev session with the doctor command. Walks the ready contract, control channel, token, executor, and browser checks in order. Use `doctor` to find out why a dev session (or an automation verb talking to it) is not working. `doctor` walks the control-channel legs of a dev session in dependency order (from the on-disk readiness contract all the way to a live probe of the in-extension executor) and names the **first failing leg** with a concrete fix, instead of the dead-end error each command gives on its own. [Extension.js: extension doctor](https://www.youtube-nocookie.com/embed/qYOkHqtreFY?rel=0) ## When to use `doctor` * `extension logs` or an act verb can't connect and you want to know which leg is broken. * An agent or script drives a session via `ready.json` and needs a machine-readable health check. * A dev session looks alive but the extension stopped responding. ## Usage ```bash npm theme={null} extension doctor [project-path] [options] ``` ```bash pnpm theme={null} extension doctor [project-path] [options] ``` ```bash yarn theme={null} extension doctor [project-path] [options] ``` ```bash bun theme={null} extension doctor [project-path] [options] ``` ```bash deno theme={null} extension doctor [project-path] [options] ``` If you omit the path, Extension.js diagnoses the session for the current working folder. ## Arguments and flags | Flag | What it does | Default | | - | - | - | | `[project-path]` | Path to the extension project root. | `process.cwd()` | | `--browser ` | Which session to diagnose (`chrome`, `chromium`, `edge`, `firefox`). | resolved (see below) | | `--output ` | Output format (`json` prints a schema-1 envelope for agents). | `pretty` | ### How `doctor` picks the session Without `--browser`, `doctor` diagnoses the session that exists, not a hardcoded default. It lists the ready contracts under `dist/extension-js/` and resolves from there: * Exactly one live contract wins outright. * With several contracts, `chromium` wins when present, otherwise the first one alphabetically. A `session-resolution` warn check then names every candidate before the numbered checks run. * With no contracts at all, `doctor` falls back to `chromium`. From the release after 4.1.39, a session that still runs wins over one that has ended. A session has ended when its contract reads `status: "stopped"` or its process is gone. With one session running and the others ended, `doctor` diagnoses the running one. When every session has ended, `doctor` diagnoses one of them by the same rule, and the `session-resolution` check says so: ```plaintext theme={null} multiple ended sessions found (chrome, firefox), diagnosing chrome ``` For a stopped session, the `ready-contract` check then fails and its remediation names the command that starts the session again. [Extension.js: extension doctor with several live sessions](https://www.youtube-nocookie.com/embed/rJy65dbY63s?rel=0) ## What it checks Checks run in dependency order. When a leg fails, later checks that depend on it are marked **skip** and name the check that blocked them: a skip is not a pass. A zeroth `session-resolution` check appears only when several live sessions exist. It warns and names the session that the run diagnoses. From the release after 4.1.39, it also appears when several sessions exist and all of them have ended. Two more checks run before the numbered ones. `engine` fails when the session runs the `chromium-emulator` target, which `doctor` cannot diagnose. `peer-rspack` needs only the project, so it runs with or without a dev session. It fails when a direct dependency declares an `@rspack/core` peer range that misses the version Extension.js ships. That mismatch is why `npm install` fails with `ERESOLVE`, and the remediation names the upgrade to run. | # | Check | What it verifies | | - | - | - | | 1 | `ready-contract` | `dist/extension-js//ready.json` exists and reports `status: "ready"`. | | 2 | `server-process` | The dev-server `pid` from the contract is still alive (a dead pid means the contract is stale). | | 3 | `port-agreement` | The persisted control port matches the live contract's `controlPort` (a mismatch strands cached service workers on the old port). | | 4 | `control-channel` | The control server accepts a connection on the contract port for this `instanceId`. | | 5 | `eval-token` | When the session runs with `--allow-eval`, the session token is readable from the project root. | | 6 | `executor` | A live probe round-trips through the extension's background context. | | 7 | `browser` | The launched browser has not exited out from under the still-running dev server. The verdict also names the binary that ran and how it was chosen (`managed`, `pinned`, `system`, or `snapshot`), which is the fastest way to catch a session using a different browser than you assumed. | Some legs have deliberate soft answers: * `port-agreement` passes when no port file exists yet. A first session for this project and browser has nothing to disagree with. * `executor` reports **warn**, not fail, within 10 seconds of a fresh compile. The service worker may still be attaching. Wait for `runtime: "attached"` in `ready.json` before acting. * `browser` reports **skip** when the contract has no `cdpPort` stamped and no exit recorded. Absence of exit evidence is not proof of a live browser. The pretty output prints one line per check plus the first failing check's remediation. Each status has a glyph: `✓` pass, `✗` fail, `!` warn, `–` skip. The exit code is `0` when nothing failed and `1` when any check failed, so CI and scripts can gate on it directly. ## Sessions from `start` and `preview` From the release after 4.1.39, `doctor` also diagnoses an `extension start` or `extension preview` session that has a control channel, which is one started with `--allow-control` or `--allow-eval`. The rows name that command where they named the dev server. Such a session runs no dev server and persists no control port, so `port-agreement` is not applicable. The row prints as a skip and leaves the pass count, and the header says so: ```plaintext theme={null} doctor (chrome), 7/7 checks passed, 1 not applicable ``` Under `--output json`, the row carries `"applicable": false`: ```json theme={null} { "check": "port-agreement", "status": "skip", "applicable": false, "detail": "not applicable: an extension preview session runs no dev server, so it persists no control port to compare" } ``` A `start` or `preview` run that holds its browser open without a control channel gives `doctor` nothing to reach. The `ready-contract` check fails, says that the command is running with no control channel, and names the command that restarts it with one: ```plaintext theme={null} extension preview --browser=chrome --allow-control ``` On Firefox, the rows say `background page` where a Chromium session says `service worker`, because Firefox runs the background as a page. ## Machine-readable output `--output json` prints one schema-1 envelope. The check results ride in `value` on both verdicts, because an unhealthy report is still a report: ```json theme={null} { "schema": 1, "ok": false, "command": "doctor", "status": "unhealthy", "value": [ { "check": "ready-contract", "status": "pass", "detail": "status ready, controlPort 43021, instanceId a1b2c3" }, { "check": "server-process", "status": "fail", "detail": "dev-server pid 4242 is dead, ready.json is stale", "remediation": "A previous dev session died uncleanly; restart it: extension dev --browser=chromium --allow-control" } ], "error": { "code": "E_SESSION_NOT_FOUND", "message": "1 of 7 doctor checks failed." }, "hint": "A previous dev session died uncleanly; restart it: extension dev --browser=chromium --allow-control", "warnings": [] } ``` A healthy run answers `ok: true` with `status: "healthy"` and `error: null`. `status` on each check is `pass`, `fail`, `warn`, or `skip`. `remediation` is present on failures that have a known fix. The envelope's `error.code` maps from the first failing check: | First failing check | `error.code` | | - | - | | `engine` | `E_COMMAND_UNSUPPORTED_FOR_TARGET` | | `peer-rspack` | `E_DEPENDENCY_INSTALL` | | `ready-contract`, `server-process` | `E_SESSION_NOT_FOUND` | | `port-agreement`, `control-channel`, `executor` | `E_CONTROL_UNAVAILABLE` | | `eval-token` | `E_TOKEN_MISSING` | | `browser` | `E_BROWSER_LAUNCH` | ## Typical flow 1. Start a session: `extension dev --browser=chromium --allow-control` (add `--allow-eval` for the eval verb). 2. When a follow-up command can't reach it, run `extension doctor` from the same project root. 3. Apply the remediation printed for the first failing check, then re-run `doctor` to confirm. ## Next steps * Read the readiness contract `doctor` starts from in [`dev`](/docs/commands/dev#automation-metadata-recommended-for-scriptsagents). * Stream extension logs from a healthy session with [Debugging](/docs/debugging). * Review shared flags in [Global flags](/docs/workflows/global-flags). # Eval command for extension contexts Source: https://extension.js.org/docs/commands/eval Run a JavaScript expression inside any context of a running Extension.js dev session, from the background worker to a live page, straight from the terminal. Run a JavaScript expression inside a context of a running dev session and print the result. `eval` is the most powerful automation verb, so it is double locked. The session must be started with `extension dev --allow-eval`, and the CLI must present the session token that the dev server wrote for this project and browser. Both happen automatically when you run the two commands from the same project root. ## When to use `eval` * You want to poke at extension state (`chrome.runtime`, storage, DOM) without opening DevTools. * An agent needs to run a check inside the page and get a structured value back. * You want a scriptable REPL against the background worker or a live tab. ## Usage ```bash npm theme={null} extension eval [project-path] [options] ``` ```bash pnpm theme={null} extension eval [project-path] [options] ``` ```bash yarn theme={null} extension eval [project-path] [options] ``` ```bash bun theme={null} extension eval [project-path] [options] ``` ```bash deno theme={null} extension eval [project-path] [options] ``` For example, read the title and URL of the active tab from inside the page: ```bash theme={null} extension eval "({title: document.title, url: location.href})" --context page ``` ## Arguments and flags | Flag | What it does | Default | | - | - | - | | `` | The JavaScript expression to evaluate. | required | | `[project-path]` | Path to the extension project root. | `process.cwd()` | | `--context ` | Target context: `background`, `popup`, `options`, `sidebar`, `devtools`, `newtab`, `history`, `bookmarks`, `content`, `page`. | `background` | | `--url ` | For `content`/`page`: the document to target, resolved to its tab. | unset | | `--tab ` | For `content`/`page`: a specific tab. Without it, the `--url` match wins, else the active tab. | active tab | | `--browser ` | Which session to target (`chrome`, `chromium`, `edge`, `firefox`). | `chromium` | | `--timeout ` | Command timeout in milliseconds. | `5000` | | `--output ` | Output format (`json` wraps the result in the schema-1 envelope). | `pretty` | Extension pages (`popup`, `options`, `sidebar`, `devtools`, `newtab`, `history`, `bookmarks`) answer through their own in-page relay, so the surface must be open in the browser. Use `open` (documented in [Trigger actions and commands](/docs/debugging/trigger-actions-and-commands)) to open one first. The devtools page runs only while DevTools is open on a tab, and `open` cannot open DevTools. From the release after 4.1.39, the refusal for a closed surface names a step that works on that browser: | Surface | Chromium | Firefox | | - | - | - | | Popup | Click the extension's toolbar entry, or its row in the extensions menu | `extension open popup` | | Side panel or sidebar | Click the extension's toolbar entry, or its row in the extensions menu | The sidebar button in the toolbar, or View > Sidebar | | Options page | `extension open options` | `extension open options` | On Firefox, an extension document whose policy forbids eval answers through the debugger protocol instead. Since 4.1.32 that route also takes a statement list: it answers the completion value of the last statement and awaits a promise the statements end on. A result past 256 KiB comes back as a 1024 character preview with `truncated: true` on the envelope, and pretty output prints a `result truncated (byte cap)` line. From the release after 4.1.39, `--context page` also evaluates in a tab that shows one of your extension's own pages, on Chrome and Firefox. A browser refuses to inject a script into an extension page, so the CLI uses the browser's debugger port. It needs exactly one open tab on that URL. `--context content` on such a tab fails with a hint that names `--context page`. Pretty output prints the value itself: strings as-is, everything else as indented JSON. The envelope shape appears only under `--output json` (see [Result envelope](/docs/contracts/result-envelope)). The value crosses as JSON. From the release after 4.1.39, a circular reference inside the value arrives as `null`. ## How the unlock works 1. `extension dev --allow-eval` starts the session with eval enabled. `--allow-eval` also unlocks the other control verbs, so you do not need both flags. 2. The dev server writes a random session token to `.extension-js/control-token-` with `0600` permissions. The token is keyed per browser, so concurrent sessions do not collide. 3. `eval` reads that token from the project root and presents it during the handshake. A session started without `--allow-eval` refuses the call, and the refusal names `--allow-eval` as the flag to add. A missing token fails with `E_TOKEN_MISSING`, a mismatched or disabled one with `E_EVAL_REFUSED`. ## Failure modes * The expression threw inside the target: `E_EVAL`, with a hint that the expression itself is at fault. This is a result, not a transport error. * A content security policy forbids eval in the target: `E_CSP_BLOCKS_EVAL`. An MV3 extension forbids eval in its own documents and content scripts, and a web page can forbid it for itself. On Firefox, the CLI evaluates an extension document through the debugger protocol when the extension's policy forbids eval. Read the target with [`inspect`](/docs/commands/inspect) when you get this code. Since 4.1.32, Firefox also evaluates a web page that forbids eval for itself through the debugger, when exactly one open tab is on that url. With a duplicate tab open the call keeps the refusal and the hint names the tab to close. * No session for the browser: `E_SESSION_NOT_FOUND`, with the exact `extension dev` command to run. * From the release after 4.1.39, a session that has ended answers `E_SESSION_NOT_FOUND` too, and the message prints the command that starts it again. See [When the session has ended](/docs/debugging#when-the-session-has-ended). * Target surface not open, or a stale `--tab` id: `E_TARGET_NOT_FOUND`. Use [`inspect --list-tabs`](/docs/commands/inspect#the-discovery-loop) to find live ids. * The manifest declares no page for the context: `E_TARGET_NOT_FOUND`. From the release after 4.1.39, the message says `the manifest declares no page`, and the hint names the manifest key to add. * From the release after 4.1.39, an MV3 `start` or `preview` build whose manifest has no `scripting` permission refuses `--context content` and `--context page`. The message tells you to add `"scripting"` to `permissions`, or to use a dev session, which adds it. `--context background` still works. A `--tab` id that does not exist answers `E_TARGET_NOT_FOUND` on such a build too. * The call outlived `--timeout`: `E_TIMEOUT`. The exit code is `0` when the expression succeeds and `1` otherwise, so scripts can gate on it directly. Run [`doctor`](/docs/commands/doctor) when every verb fails and you want the broken leg named. ## Next steps * Find tab ids and DOM state to target with [`inspect`](/docs/commands/inspect). * Read or write `chrome.storage` without writing an expression with [`storage`](/docs/commands/storage). * Read the wider debugging workflow in [Debugging](/docs/debugging). * Review the machine output format in [Result envelope](/docs/contracts/result-envelope). # Extension.js command guide Source: https://extension.js.org/docs/commands/index Reference for every Extension.js CLI command including dev, build, start, preview, create, install, and uninstall with usage examples. Choose the right command for the current phase of extension development, from first scaffold to production validation. ## Command chooser | Goal | Command | Example | | - | - | - | | Scaffold a new project | `create` | `npx extension@latest create my-extension --template=newtab-react` | | Develop with watch mode | `dev` | `extension dev --browser=firefox` | | Build production artifacts | `build` | `extension build --browser=chrome,firefox --zip` | | Build and launch production output | `start` | `extension start --browser=edge` | | Launch existing build output only | `preview` | `extension preview --browser=chrome` | | Get a shareable URL for a project | `publish` | `extension publish --ttl=4` | | Install a managed browser runtime | `install` | `extension install chrome` | | Remove a managed browser runtime | `uninstall` | `extension uninstall chrome` | | Diagnose a running dev session | `doctor` | `extension doctor --browser=chromium` | | Read or stream session logs | `logs` | `extension logs --follow --context background,content` | | List tabs or inspect a DOM | `inspect` | `extension inspect --tab 412 --with-console` | | Run code in a live context | `eval` | `extension eval "location.href" --context page` | | Read or write extension storage | `storage` | `extension storage get --key settings` | | Reload a context on demand | `reload` | `extension reload --context background` | | Open a surface or replay an action | `open` | `extension open popup` | | Point a tab at a url | `navigate` | `extension navigate https://example.com/ --new-tab` | | Handshake for scripts and agents | `capabilities` | `extension capabilities` | Running a bare `extension` with no command prints the full help and exits with code `0`. ## Typical developer flow 1. `create` to scaffold. 2. `dev` for iterative coding and reload cycles. 3. `build` for production artifacts. 4. `preview` or `start` for production-like validation. 5. `install` or `uninstall` when you need to manage Extension.js browser runtimes explicitly. 6. `logs`, `inspect`, `eval`, `storage`, `reload`, `open`, and `navigate` to observe and drive the running session. 7. `doctor` when a dev session or an automation verb talking to it stops responding. 8. `capabilities` first, when a script or agent drives the CLI instead of a human. ## Command references * [create](/docs/commands/create) * [dev](/docs/commands/dev) * [build](/docs/commands/build) * [start](/docs/commands/start) * [preview](/docs/commands/preview) * [publish](/docs/commands/publish) * [install](/docs/commands/install) * [uninstall](/docs/commands/uninstall) * [doctor](/docs/commands/doctor) * [logs](/docs/commands/logs) * [inspect](/docs/commands/inspect) * [eval](/docs/commands/eval) * [storage](/docs/commands/storage) * [reload](/docs/commands/reload) * [open](/docs/debugging/trigger-actions-and-commands) * [navigate](/docs/workflows/driving-the-cli#step-4-act-and-read-envelopes) * [capabilities](/docs/commands/capabilities) The `telemetry` command (`enable` / `disable` / `status`) manages anonymous telemetry consent. See [Telemetry and privacy](/docs/features/telemetry-and-privacy). ## Next steps * Apply cross-command controls in [Global flags](/docs/workflows/global-flags). * Keep defaults centralized in [Extension configuration](/docs/features/extension-configuration). # Inspect command for DOM and tab discovery Source: https://extension.js.org/docs/commands/inspect Inspect a page or content DOM from the terminal with the Extension.js inspect command. List tabs, fetch HTML summaries, and attach recent console lines. Inspect a page or content DOM through the agent bridge, without CDP and without opening DevTools. `inspect` asks a running dev session what a document looks like right now. It can list open tabs, return a structural summary or raw HTML, and attach the last console lines for the same target. The session must run with the control channel unlocked: start it with `extension dev --allow-control`. A refusal names the missing flag, so a denied call tells you exactly how to restart the session. [Extension.js: extension inspect](https://www.youtube-nocookie.com/embed/AwDHHXSqDNs?rel=0) ## When to use `inspect` * You want to confirm what your content script actually rendered into a page. * An agent needs tab ids to target [`eval`](/docs/commands/eval) or `inspect` calls precisely. * You want DOM state and the matching console tail in one machine-readable result. ## Usage ```bash npm theme={null} extension inspect [project-path] [options] ``` ```bash pnpm theme={null} extension inspect [project-path] [options] ``` ```bash yarn theme={null} extension inspect [project-path] [options] ``` ```bash bun theme={null} extension inspect [project-path] [options] ``` ```bash deno theme={null} extension inspect [project-path] [options] ``` ## Arguments and flags | Flag | What it does | Default | | - | - | - | | `[project-path]` | Path to the extension project root. | `process.cwd()` | | `--context ` | What to inspect: `content`, `page`, or an open surface (`popup`, `options`, `sidebar`, `devtools`, `newtab`, `history`, `bookmarks`). | `content` | | `--url ` | For `content`/`page`: the document to target, resolved to its tab. | unset | | `--tab ` | For `content`/`page`: a specific tab. Without it, the `--url` match wins, else the active tab. | active tab | | `--list-tabs` | List open tabs as `{id, url, title, active, windowId}` and exit. | off | | `--include ` | Comma-separated result parts: `html`, `summary`. | `summary` | | `--max-bytes ` | Cap on returned HTML bytes. From the release after 4.1.39, a value above `262144` is lowered to `262144`. | `262144` | | `--with-console [n]` | Also include the last `n` console lines for the target. | `20` when set | | `--browser ` | Which session to target (`chrome`, `chromium`, `edge`, `firefox`). | `chromium` | | `--timeout ` | Command timeout in milliseconds. | `5000` | | `--output ` | Output format (`json` wraps the result in the schema-1 envelope). | `pretty` | There is no `--deep-dom` flag. Deep DOM support is a bridge capability the session reports internally, not something you toggle per call. ### Your extension's own pages in a tab From the release after 4.1.39, `--context page` also reads a tab that shows one of your extension's own pages. This works on Chrome and Firefox. A browser refuses to inject a script into an extension page. The CLI reads that tab over the browser's debugger port instead, and it needs exactly one open tab on that URL. On Firefox, it finds the page through `extensionBaseUrl` in [`ready.json`](/docs/contracts/ready-json). `--context content` on such a tab fails with a hint, because an extension page has no content script world. A tab that shows a page of another extension stays out of reach. ## The discovery loop Numeric tab ids make targeting deterministic. The intended flow is list first, then inspect: ```bash theme={null} extension inspect --list-tabs extension inspect --tab 412 --with-console ``` `--list-tabs` needs the unlocked control channel but no eval token, so it works in any `--allow-control` session. The result is an array of `{id, url, title, active, windowId}` objects. Feed the `id` value straight into `--tab` here or in `eval`. ## Console augmentation `--with-console` merges a `console` array into the result: the last `n` log records for the same context and tab, read from the session's `logs.ndjson`. This gives an agent DOM state and console evidence in a single round trip. The augmentation is best effort and never fails the command. Both output modes show it. Pretty mode prints the console lines after the DOM summary in the same `[seq] LEVEL (context) message` format `logs` uses, or `(no console lines captured)` when the tail is empty. `--output json` carries the raw records in the envelope's `console` array. ## Truncation HTML larger than `--max-bytes` comes back truncated. Pretty mode prints a truncation notice on stderr, and `--output json` sets `truncated: true` in the envelope (see [Result envelope](/docs/contracts/result-envelope)). From the release after 4.1.39, one result carries at most 256 KB, and `--max-bytes` cannot raise that. A value above `262144` is lowered to it, and a `warnings` entry says so. The cap counts the whole result as JSON, and markup grows when it is escaped. HTML under `--max-bytes` can still be cut to fit. The result then carries `truncated: true`, `value.htmlTruncated: true`, and a `warnings` entry that gives the `eval` call to read the rest: ```plaintext theme={null} html cut to 180000 of 400000 characters to fit the 262144-byte result cap. Read on with eval: document.documentElement.outerHTML.slice(180000, 380000) ``` ## Failure modes * No session found for the browser: `E_SESSION_NOT_FOUND`, with the exact `extension dev` command to run. * From the release after 4.1.39, a session that has ended answers `E_SESSION_NOT_FOUND` too, and the message prints the command that starts it again. See [When the session has ended](/docs/debugging#when-the-session-has-ended). * Session running without `--allow-control`: the connection is refused and the error names the flag. * Target surface not open, or a `--tab` id that no longer exists: `E_TARGET_NOT_FOUND`. * From the release after 4.1.39, the refusal for a closed surface names a step that works on that browser. See the table in [`eval`](/docs/commands/eval#arguments-and-flags). * From the release after 4.1.39, an MV3 `start` or `preview` build whose manifest has no `scripting` permission refuses `--context content` and `--context page`. The message tells you to add `"scripting"` to `permissions`, or to use a dev session, which adds it. A `--tab` id that does not exist answers `E_TARGET_NOT_FOUND` on such a build too. * `--context background` is refused on every browser. On Chromium, the reason is that the service worker has no DOM. On the other browsers, it is that the background has no page to read. Inspect a content script or a page with `--tab`, or an open surface. * The target took longer than `--timeout`: `E_TIMEOUT`. Run [`doctor`](/docs/commands/doctor) when the same session refuses every verb and you want the first broken leg named. ## Next steps * Run an expression in the page that you just inspected with [`eval`](/docs/commands/eval). * Stream the same session's logs continuously with [`logs`](/docs/commands/logs). * Read the wider debugging workflow in [Debugging](/docs/debugging). # Install command for managed browser runtimes Source: https://extension.js.org/docs/commands/install Add a managed browser runtime to the Extension.js cache for deterministic builds. Supports Chrome for Testing, Chromium, Firefox, and Edge. Use `install` to add a managed browser runtime into the Extension.js cache. This is most useful when you want a consistent browser binary for `dev`, `build`, `start`, or `preview`. It supports Chrome for Testing, Chromium, Firefox, and Edge. [Extension.js: extension install chrome](https://www.youtube-nocookie.com/embed/MlFYdIQkxkk?rel=0) ## When to use `install` * You need a consistent, repeatable browser binary for continuous integration (CI), automation, or team-consistent local runs. * You want Chrome for Testing instead of relying on whatever Chrome version your system has installed. * You are setting up cross-browser testing with a managed Firefox, or with Edge. ## Why Extension.js downloads a browser The run commands prefer a managed browser runtime over the browser that you use every day. * The managed binary is version-pinned. `dev`, CI runs, and teammates all launch the same build. * Chrome for Testing is built for automation. Recent branded Chrome builds (150+) can drop the `--load-extension` switch that loads your extension. * The managed runtime runs in an isolated profile. It never touches your personal browser, its profile, or its settings. You do not have to run `install` up front. When no usable binary exists for the requested target, the run commands print the exact install command. ## Skip the managed download You can develop against a browser that is already installed, with no download: * Run a fork by name: `extension dev --browser=brave` locates the installed Brave for you. See [Running other browsers](/docs/browsers/running-other-browsers). * Pin any binary: pass `--chromium-binary ` or `--gecko-binary ` to `dev`, `start`, or `preview`. The pin overrides every locator. * Set a binary variable such as `FIREFOX_BINARY`. See [Which binary runs](#which-binary-runs). * Requested `edge` launches the Edge that is installed on your system. * Requested `chrome` refuses a branded system Chrome and asks for Chrome for Testing instead. * To run branded Chrome anyway, pin it with `--chromium-binary`. ### Edge installs on your system `extension install edge` runs `playwright install msedge`, which installs Microsoft Edge on your system. The Extension.js cache holds no pinned copy of Edge. `--browser=edge` finds the system Edge on its own, so you can skip the command when Edge is already installed. On Linux, that install needs an interactive session with sudo rights. When the install fails and a system Edge exists, the installer reports the system binary and succeeds with it. ## Which binary runs From the release after 4.1.39, `dev`, `start`, and `preview` choose the binary in one order for every browser: 1. The flag, `--chromium-binary` or `--gecko-binary`. 2. The environment variable of the browser. 3. The managed binary from `extension install`. 4. The system install. | Browser | Variables, in the order that they are read | | - | - | | `chrome` | `CHROME_FOR_TESTING_PATH`, `CHROMIUM_BINARY`, `CHROME_BINARY` | | `chromium` | `CHROMIUM_BINARY` | | `edge` | `EDGE_BINARY` | | `firefox` | `FIREFOX_BINARY` | A variable that names a missing path, or a file that cannot run, fails the launch with `E_BROWSER_BINARY_INVALID`. A bad variable is never skipped. The identity card says which step answered. `(pinned with FIREFOX_BINARY)` names the flag or the variable, and `(system install)` marks a browser from your system. A managed binary gets no note. `ready.json` carries the same fact in `binaryProvenance` and `binaryPinnedBy`. For Firefox, the managed step prefers a stable build over a nightly that sits in the same cache. When a nightly runs, the card says `Firefox Nightly`. Requested `chrome` still refuses a branded system Chrome. A variable that names branded Chrome is not taken, and the run continues with the managed binary. See [How the binary is chosen](/docs/browsers/browsers-available#how-the-binary-is-chosen). ## Canonical usage For a single browser, use the positional form: ```bash npm theme={null} extension install ``` ```bash pnpm theme={null} extension install ``` ```bash yarn theme={null} extension install ``` ```bash bun theme={null} extension install ``` ```bash deno theme={null} # Needs Node.js on PATH: the download runs through npx. extension install ``` Use `--browser` only when you need multiple targets, browser families, or `all`. ## Install command capabilities | Capability | What it gives you | | - | - | | Managed browser cache | Stable install location under the Extension.js browser cache | | Repeatable runtime | Consistent binaries for repeatable local runs and automation | | Cross-browser setup | One command flow for Chrome, Chromium, Edge, and Firefox | | Path discovery | `--where` reveals the resolved cache root or browser-specific install path | ## Usage ```bash npm theme={null} extension install [browser-name] [options] ``` ```bash pnpm theme={null} extension install [browser-name] [options] ``` ```bash yarn theme={null} extension install [browser-name] [options] ``` ```bash bun theme={null} extension install [browser-name] [options] ``` ```bash deno theme={null} # Needs Node.js on PATH: the download runs through npx. extension install [browser-name] [options] ``` ## Arguments and flags | Flag / argument | What it does | Default | | - | - | - | | `[browser-name]` | Install a single browser target such as `chrome`, `chromium`, `edge`, or `firefox` | `chromium` | | `--browser ` | Override the positional browser name and support multi-target installs | unset | | `--where` | Print the resolved managed cache root, or browser-specific install path | disabled | | `--output ` | Result format. `json` prints a schema-1 envelope on stdout | `pretty` | ### What `all` means here `extension install --browser all` installs `chrome`, `chromium`, `edge`, and `firefox`. This differs from `--browser all` on the run commands, which expands to `chrome`, `edge`, and `firefox` only. The install set also covers Chromium because it is the default launch target for `dev` and `start`. ## Machine output with `--output json` `--output json` prints one schema-1 envelope on stdout: * A successful install prints a `status: "installed"` frame with the installed browsers in `value.browsers`. * `--where` prints a `status: "located"` frame with the resolved paths in `value.paths`. * A failed download prints `ok: false` with `error.code: "E_BROWSER_DOWNLOAD"` before the process exits `1`. * A download that finishes without leaving a usable browser binary fails the same way. See [Behavior notes](#behavior-notes). ## Examples ### Install Chrome for Testing ```bash theme={null} extension install chrome ``` ### Install multiple targets in one command ```bash theme={null} extension install --browser chrome,firefox ``` ### Show the managed install path for Chrome ```bash theme={null} extension install chrome --where ``` ## Cache locations By default, Extension.js stores managed browsers in a stable per-user cache: * macOS: `~/Library/Caches/extension.js/browsers` * Linux: `~/.cache/extension.js/browsers` or `$XDG_CACHE_HOME/extension.js/browsers` * Windows: `%LOCALAPPDATA%\extension.js\browsers` You can override the cache root with `EXT_BROWSERS_CACHE_DIR`. ### What the cache holds Each browser gets its own folder under the cache root, but the layout inside differs by download engine: * `chrome`, `chromium`, and `firefox` come from `@puppeteer/browsers`. Expect its nested platform and version folders inside each browser directory. * `edge` is not in the cache. `playwright install msedge` installs Microsoft Edge on your system. * `safari` has no download. Safari ships with macOS and needs the full Xcode app for builds, so `extension install safari` refuses with an explanation. * Named forks such as Brave are never downloaded. Point at them with `--chromium-binary` or `--gecko-binary` instead. Use `--where` instead of hardcoding paths, because the nested layout can change with the download engines. ### Project-local binaries Set `EXTENSIONJS_BINARIES_IN_DIST=1` to make the run commands resolve managed binaries under `dist/extension-js/binaries` inside the project instead of the shared per-user cache. This suits sandboxed or fully self-contained project setups. ## Best practices * **Use `install` in CI** to pin a consistent browser binary instead of relying on whatever the runner provides. * **Prefer `chrome`** over `chromium` for Chrome for Testing: it matches stable Chrome behavior more closely. * **Use `--where`** to verify cache paths before scripting automation around managed browsers. * `install` keeps `chrome`, `chromium`, and `firefox` inside the Extension.js cache. It leaves system installs of those browsers alone. * `edge` is the exception. It installs Microsoft Edge on your system. ## Behavior notes * `chrome` installs Chrome for Testing rather than relying on the system Google Chrome app. * `edge` may require a privileged interactive session on Linux. * `install` checks the destination before it reports success. When the installer exits cleanly but the folder holds no browser binary that is a non-empty executable file, as after an interrupted download, the command fails with `E_BROWSER_DOWNLOAD` and exits `1`. It removes the incomplete files, so the next `extension install` starts clean. * On Deno, `install` needs Node.js on your `PATH`. The browser installer shells out to `npx`, or to the package manager that launched the CLI, to run the download engine, and `deno` has no such runner. Without Node.js the command fails at the download step. The other commands run on Deno alone. ## Next steps * Remove managed browsers with [`uninstall`](/docs/commands/uninstall). * Use managed browsers with [`dev`](/docs/commands/dev) and [`start`](/docs/commands/start). * Learn about [Running other browsers](/docs/browsers/running-other-browsers) with custom binary paths. # Logs command for reading dev session output Source: https://extension.js.org/docs/commands/logs Print or stream logs from every context of a running Extension.js dev session. Filter by context, level, URL, or tab, and pipe ndjson to tools. Print or stream logs from every context of a running dev session. `logs` is a command of the Extension.js CLI. Extension.js builds and runs browser extensions from one `manifest.json` for Chrome, Edge, Firefox, and Safari, and `npx extension@latest dev` starts the session that this command reads. `logs` reads the log records that a [`dev`](/docs/commands/dev) session collects from your extension: background, content scripts, popup, options, and the rest. One command shows them all, merged in order, without opening a single DevTools window. [Extension.js: extension logs --follow](https://www.youtube-nocookie.com/embed/R5RZ1vxLBTA?rel=0) ## When to use `logs` * You want console output from the background worker and a content script in one stream. * An agent or script needs machine-readable log records instead of screen-scraped terminal text. * You want to check what an extension logged earlier without re-triggering the behavior. ## Usage ```bash npm theme={null} extension logs [project-path] [options] ``` ```bash pnpm theme={null} extension logs [project-path] [options] ``` ```bash yarn theme={null} extension logs [project-path] [options] ``` ```bash bun theme={null} extension logs [project-path] [options] ``` ```bash deno theme={null} extension logs [project-path] [options] ``` By default, `logs` prints the records already on disk and exits. Add `--follow` to stay attached and stream new records live. ## Arguments and flags | Flag | What it does | Default | | - | - | - | | `[project-path]` | Path to the extension project root. | `process.cwd()` | | `--browser ` | Which session to read (`chrome`, `chromium`, `edge`, `firefox`, `safari`). | `chromium` | | `--follow` | Stream live over the control channel instead of printing and exiting. | off | | `--context ` | Comma-separated contexts (`background`, `content`, `page`, `popup`, `options`, `sidebar`, `devtools`, `newtab`, `history`, `bookmarks`). A name outside this list is refused with `E_INVALID_OPTION`. | all contexts | | `--level ` | Minimum severity (`off`, `error`, `warn`, `info`, `debug`, `trace`, `all`). | `all` | | `--signals-only` | Experimental. Show only structured `dx.signal` diagnostics. No emitter ships yet, so this currently prints nothing. | off | | `--since ` | Only show events after this sequence number, or after this ISO timestamp by the event clock. | unset | | `--url ` | Only events whose URL or hostname matches (glob with `*`, or a plain substring). | unset | | `--tab ` | Only events from this tab id. | unset | | `--output ` | Output format. | `pretty` on a TTY, `ndjson` when piped | Choosing a `--level` includes that level plus everything more severe. `--level warn` shows `warn` and `error`. Plain `console.log` records count as `info`. From 4.1.20, a Safari session is read the same way. `extension logs --browser safari` prints the background and content rows of a `dev --browser safari` session, and `--follow` streams them. See [Building Safari extensions](/docs/browsers/safari). ## One-shot mode Without `--follow`, the command reads `dist/extension-js//logs.ndjson` directly and needs no live connection. The dev session appends every record to that file, so a one-shot read works even after you close the browser. If the file does not exist, `logs` prints a hint to start `extension dev` first and exits with code `1`. Machine formats also emit a failure envelope with code `E_LOGS_NOT_FOUND` (see [Result envelope](/docs/contracts/result-envelope)). From the release after 4.1.39, when another browser of the same project has a log file, the refusal names it: ```plaintext theme={null} Logs exist for chromium: pass --browser chromium to read them. ``` A log file outlives its session. The hint says that there is something to read for that browser, not that its session is up. When the session dropped records, the file holds a gap record in their place. An unfiltered `ndjson` or `json` read prints that record on stdout as it is. Once any filter narrows the read (`--context`, `--level`, `--since`, `--url`, `--tab`), stdout carries log records only, and the loss is reported as one line on stderr with the drop count and reason, in every output format. ## Follow mode `--follow` looks up the session's readiness contract, connects to the control channel as a log consumer, and streams records as they happen. It needs a running dev session, but no unlock flag: log consumption is always allowed. ```bash theme={null} extension logs --follow --context background,content --level info ``` If the stream falls behind and the session drops records, `logs` prints a one-line gap notice on stderr with the drop count and reason. When you stop the stream with `Ctrl+C`, machine formats print one terminating success envelope with status `interrupted`, so a consumer can tell a clean stop from a crash. The exit code is `0`. If no session is found for the chosen browser, the command fails with `E_SESSION_NOT_FOUND` and names the `extension dev` command to run. From the release after 4.1.39, a session that has ended fails the same way. The message says that the session ended and prints the command that starts it again, which is `extension dev`, `extension start`, or `extension preview`. The hint `A session is running for ` appears only when that browser's session is up and its control port answers. See [When the session has ended](/docs/debugging#when-the-session-has-ended). ## Output formats Pretty mode prints one line per record: ```plaintext theme={null} [142] INFO (background) message text from the worker [143] ERROR (content) E_SOMETHING failed to reach the page ↳ remediation hint, when the record carries one ``` `ndjson` prints one raw JSON record per line, ideal for `jq` and log shippers. `json` pretty-prints each record over multiple lines. When stdout is not a TTY, `ndjson` is already the default, so piping needs no extra flag: ```bash theme={null} extension logs --context content | jq -r '.messageParts | join(" ")' ``` ## Tell content script rows from service worker rows Without `logs`, the two outputs live in two DevTools windows: the service worker console behind the extensions page, and the content script console inside the page that it runs in. `logs` merges them into one stream and labels every record with the context that produced it, so you can split them again on your terms. The label is the `context` field, printed in parentheses in pretty mode. The dev session assigns it per compiled entry. Output under `content_scripts/` is `content`, and the background service worker (or the Firefox background script) is `background`. `action/index.js` is `popup`, `options/index.js` is `options`, and so on through the list that `--context` accepts. ```plaintext theme={null} [142] LOG (background) [From the background context] Hello from the background worker/script! [143] LOG (content) [From the page context] Hello from content_scripts! ``` A `console.log` call prints as `LOG` and is filtered as `info`, so `--level info` keeps it and `--level warn` drops it. Two things differ between the rows beyond the label. A content script record also carries the page that it ran in (`url`, `tabId`, `frameId`). The content script relays its output to the service worker, and the session records the sender. A background record has no page, so it carries none of those fields. That gives you two ways to separate the streams: * `--context` chooses by label. `--context background` shows the service worker alone, `--context content` the content scripts alone, and a comma-separated list combines them. A name outside the list is refused. * `--url` and `--tab` choose by page. A background row has no URL or tab, so either filter drops it and leaves content rows only. ```bash theme={null} extension logs --context background --follow extension logs --context content --tab 7 --follow ``` Run those in two terminals to watch each side live, or read them one shot from the same file. Uncaught errors and unhandled rejections from either context arrive as `error` rows with the stack appended to the message, so `--level error` across both contexts is the fastest way to see which side threw. To split the stream in a script, read `ndjson` and branch on the `context` field. The `url` field is absent on background rows: ```bash theme={null} extension logs --output ndjson | jq -r '[.context, (.url // "-"), (.messageParts | join(" "))] | @tsv' ``` The same labels and filters apply to the stream that `dev` prints in its own terminal through `--logs` and `--log-context`. See [`dev`](/docs/commands/dev). ## Examples Show only errors and warnings from content scripts on a specific site: ```bash theme={null} extension logs --context content --level warn --url "*.example.com" ``` Resume reading after a known record, useful for polling agents: ```bash theme={null} extension logs --since 142 --output ndjson ``` ## Next steps * Diagnose a session that `logs --follow` cannot reach with [`doctor`](/docs/commands/doctor). * Grab a DOM snapshot with the recent console tail in one call with [`inspect`](/docs/commands/inspect). * Read the wider debugging workflow in [Debugging](/docs/debugging). * Review the machine failure format in [Result envelope](/docs/contracts/result-envelope). # Preview command to launch built extensions Source: https://extension.js.org/docs/commands/preview Launch an already-built extension for production-like manual testing without recompiling. Load unpacked output and run the browser launcher flow. Launch an already-built extension output for production-like manual testing. `preview` does not compile your project. It loads an existing unpacked extension root and runs the browser launcher flow. ## When to use `preview` * Running existing build output without rebuilding. * Comparing packaged behavior across browser targets quickly. * Debugging runtime issues tied to production artifacts rather than dev/watch mode. ## Preview command capabilities | Capability | What it gives you | | - | - | | Build-output validation | Test real production artifacts without rebuilding | | Browser-target checks | Run compiled output against selected browser targets | | Runner control | Launch or skip browser runner based on workflow needs | | Fast manual QA | Verify packaging-ready behavior quickly before release | > `preview` is run-only. It prefers `dist/` when that output exists. You can also point it at another unpacked extension folder that already contains a `manifest.json`. ## Usage ```bash npm theme={null} extension preview [project-path] [options] ``` ```bash pnpm theme={null} extension preview [project-path] [options] ``` ```bash yarn theme={null} extension preview [project-path] [options] ``` ```bash bun theme={null} extension preview [project-path] [options] ``` ```bash deno theme={null} extension preview [project-path] [options] ``` If you omit the path, Extension.js uses the current working folder. ## How `preview` chooses what to run `preview` checks these locations in order: 1. `--output-path ` when you pass it. It wins over everything else. 2. `dist/` for the selected browser target. 3. The provided project path or current working folder. The folder needs to contain an unpacked extension with a `manifest.json`. It does not matter whether a build ran in the same command. ## Arguments and flags | Flag | Alias | What it does | Default | | - | - | - | - | | `[path]` | - | Preview built extension from a project path. | `process.cwd()` | | `--browser ` | - | Browser/engine target (`chromium`, `chrome`, `edge`, `firefox`, etc.). | `commands.preview.browser`, else `chromium` | | `--profile ` | - | Browser profile path or boolean profile mode. | fresh profile | | `--chromium-binary ` | - | [Custom Chromium-family binary path](/docs/browsers/running-other-browsers). | managed install, then system install | | `--gecko-binary ` | `--firefox-binary` | [Custom Gecko-family binary path](/docs/browsers/running-other-browsers). | managed install, then system install | | `--starting-url ` | - | Starting URL in launched browser. | unset | | `--no-open` | - | Launch the browser, but do not open a tab for your extension. The browser still starts and loads it. See [stop the browser from launching](#stop-the-browser-from-launching). | a tab opens on launch | | `--no-browser` | - | Stop the browser from launching. See [stop the browser from launching](#stop-the-browser-from-launching). | browser launch enabled | | `--port ` | - | Runner/devtools port when runner is enabled. Use `0` for OS-assigned port. | `8080` | | `--extensions ` | - | Comma-separated companion extensions or store URLs. | unset | | `--allow-control` | - | Open the agent-bridge control channel on the previewed build for the act verbs (`storage`, `reload`, `open`). The browser loads a copy of the build with the control producer added, the build folder is unchanged. | disabled | | `--allow-eval` | - | Also enable `extension eval` on the previewed build. Implies `--allow-control` and writes a `0600` session token. | disabled | | `--output-path ` | - | Existing unpacked extension directory to run. | `dist/` when available | | `--output ` | - | Result format. `json` prints a schema-1 envelope on stdout. | `pretty` | | `--debug` | - | Enable maintainer diagnostics. | disabled | On Firefox, `--starting-url` opens after the add-on installs, so your `document_start` content scripts run on that page. From the release after 4.1.39, it no longer replaces a tab that your extension opened. `--author` and `--author-mode` are hidden, deprecated aliases for `--debug`. ## Browser support `preview` has no Safari path. Passing `--browser safari` (or `webkit-based`) exits with `E_COMMAND_UNSUPPORTED_FOR_TARGET`. Safari is a supported browser, but this command cannot launch it. The reason is measured. Safari's WebDriver route does load an unpacked folder, and the background even runs, but Safari grants the extension zero host origins. Content scripts never inject, and no API call can grant the access afterwards. Use [`dev`](/docs/commands/dev) or [`build`](/docs/commands/build) for Safari targets. `preview` also refuses `chromium-emulator` and exits with `E_UNSUPPORTED_BROWSER`. The emulated Chromium page reads your build from the dev server, which `preview` does not run. Use [`dev`](/docs/commands/dev#emulated-chromium) for that target. ## Remote URLs and light mode When the path argument is a remote `http(s)` URL, `preview` sets `EXTJS_LIGHT=1` automatically. This runs the launch in light mode for downloaded extensions. Set `EXTJS_LIGHT` yourself beforehand to override this behavior. Under `--output json`, the download progress lines go to stderr, so stdout holds only the result frame. ### Where a remote archive lands A remote archive is unpacked into your cache, not into the folder you ran the command from. The folder is named after the URL path, with a short digest, so one archive always lands in the same place: | Platform | Cache folder | | - | - | | macOS | `~/Library/Caches/extension.js/previews/` | | Linux | `~/.cache/extension.js/previews/` | | Any | `$XDG_CACHE_HOME/extension.js/previews/` when `XDG_CACHE_HOME` is set | A second run of the same URL reuses the copy without downloading it again, and says so. Delete the folder to download it again. The query string of the URL, where a share token lives, is not part of the key and is never written to disk. Pass `--output-path ` to unpack into a folder of your choice instead. A folder that is already there, and was not unpacked from this URL, is refused with `E_DESTINATION_NOT_EMPTY` and left as it is. A link copied from a terminal that wrapped it can carry spaces inside the token. `preview` removes them and says so before the download. A 401 or 403 from the server is reported as a refused link, with the token's expiry when it carries one, under `E_REMOTE_ACCESS_DENIED`. ## Stop the browser from launching Two flags sound alike and do different things: | You want | Flag | What happens | | - | - | - | | No browser at all | `--no-browser` | No browser process starts. `preview` writes its readiness metadata. | | A browser, but no tab opened for your extension | `--no-open` | The browser starts and loads your extension. No tab is opened for it. | ```bash theme={null} # Stop the browser launch. npx extension@latest preview --no-browser # Launch the browser without opening a tab for the extension. npx extension@latest preview --no-open ``` `--no-browser` also has a config form, `commands.preview.noBrowser: true`, and an environment form, `EXTENSION_CLI_NO_BROWSER=1`. `dev`, `start`, and `preview` all accept both flags. ## Automation metadata `preview` writes readiness metadata to: * `dist/extension-js//ready.json` For `--no-browser` flows, this provides deterministic command state: * `starting` while command initializes * `ready` when run-only validation is complete * `error` when required output is missing or startup fails * `runId` and `startedAt` for session correlation in scripts/agents From the release after 4.1.39, with `--allow-control` or `--allow-eval`, the status stays `starting` until the extension's background connects or 10 seconds pass. Read `executorAttachedAt` to know that an act verb can run. See [the ready.json contract](/docs/contracts/ready-json#sessions-that-take-act-verbs-hold-ready). From the release after 4.1.39, a refusal from such a session names `extension preview` as the command to restart. A build with no background script or service worker cannot be controlled: the session warns at startup, and every act verb answers that the build has no background. See [Refusals on a start or preview session](/docs/debugging#refusals-on-a-start-or-preview-session). After the session ends, an act verb says so and prints the `extension preview` command that starts it again. See [When the session has ended](/docs/debugging#when-the-session-has-ended). `preview` does not provide a `--wait` gate flag. For `preview` automation, consume `ready.json` directly. ### Machine output with `--output json` `--output json` prints one schema-1 envelope on stdout: * A successful run prints a `status: "ready"` frame. Its `value` carries the list of previewed browsers, plus `projectPath` when you passed a path argument. * A project path that does not exist prints `ok: false` with `status: "usage"` and `error.code: "E_PROJECT_NOT_FOUND"`. A folder with no manifest prints the same status with `E_MANIFEST_NOT_FOUND`. Neither frame carries a hint. * When the project exists but the output path holds no unpacked extension, the frame is `ok: false` with `status: "not-found"` and `error.code: "E_PREVIEW_NO_DIST"`. Its hint says to run `extension build` first. * A bad `--chromium-binary` or `--gecko-binary` pin prints `ok: false` with `status: "usage"` and `error.code: "E_BROWSER_BINARY_INVALID"`. That covers a path that does not exist, a file that is not executable, and a binary that does not answer its version probe within 10 seconds. The command ends and leaves nothing running. * A remote URL that gives no usable archive prints `ok: false` with `status: "failed"`. The code is `E_REMOTE_ZIP_INVALID` for a reply that is not a ZIP archive, a damaged one, or one with an entry outside its folder, `E_REMOTE_FETCH_TIMEOUT` for a timeout, `E_REMOTE_ACCESS_DENIED` for a 401 or 403, and `E_REMOTE_DOWNLOAD` for a refused connection or any other HTTP error. * A browser that cannot start prints `ok: false` with `status: "failed"`. The code is `E_BROWSER_LAUNCH` when the binary is executable but the system cannot start it or Firefox exits before its debugger answers, and `E_BROWSER_CONNECT` when Firefox runs but its debugger never answers. A config file that fails to load prints the same status with `E_CONFIG_LOAD`. * Other failures print `ok: false` with `status: "failed"` before the process exits `1`. ## Logging flags These flags are experimental and may change between minor releases. | Flag | What it does | Default | | - | - | - | | `--logs ` | Minimum log level. | `off` | | `--log-context ` | Context filter (`background`, `content`, `page`, `popup`, `options`, `sidebar`, `devtools`, `newtab`, `history`, `bookmarks`). | `all` | | `--log-format ` | Logger output format. | `pretty` | | `--no-log-timestamps` | Disable timestamps in pretty mode. | timestamps enabled | | `--no-log-color` | Disable color in pretty mode. | color enabled | | `--log-url ` | Filter log events by URL substring/regex. | unset | | `--log-tab ` | Filter log events by tab ID. | unset | ## Shared global options Also supports [Global flags](/docs/workflows/global-flags). ## Examples ### Previewing a local extension [Extension.js: extension preview](https://www.youtube-nocookie.com/embed/-awORl1WfFQ?rel=0) ```bash npm theme={null} npx extension@latest preview ./my-extension ``` ```bash pnpm theme={null} pnpx extension@latest preview ./my-extension ``` ```bash yarn theme={null} yarn dlx extension@latest preview ./my-extension ``` ```bash bun theme={null} bunx extension@latest preview ./my-extension ``` ```bash deno theme={null} deno run -A npm:extension@latest preview ./my-extension ``` ### Previewing in Edge and Chrome ```bash npm theme={null} npx extension@latest preview ./my-extension --browser=edge,chrome ``` ```bash pnpm theme={null} pnpx extension@latest preview ./my-extension --browser=edge,chrome ``` ```bash yarn theme={null} yarn dlx extension@latest preview ./my-extension --browser=edge,chrome ``` ```bash bun theme={null} bunx extension@latest preview ./my-extension --browser=edge,chrome ``` ```bash deno theme={null} deno run -A npm:extension@latest preview ./my-extension --browser=edge,chrome ``` ### Preview without launching the browser ```bash npm theme={null} npx extension@latest preview ./my-extension --no-browser ``` ```bash pnpm theme={null} pnpx extension@latest preview ./my-extension --no-browser ``` ```bash yarn theme={null} yarn dlx extension@latest preview ./my-extension --no-browser ``` ```bash bun theme={null} bunx extension@latest preview ./my-extension --no-browser ``` ```bash deno theme={null} deno run -A npm:extension@latest preview ./my-extension --no-browser ``` ## Behavior notes * `preview` is run-only and never compiles the project. * `preview` prefers existing build output (`dist/`) but can fall back to another unpacked extension root. * `preview` does not run watch mode or hot module replacement (HMR). * For scripts/agents, rely on `ready.json` and avoid parsing terminal output. ## Best practices * Run `build` before `preview` when testing a fresh production artifact. * Pass the project path argument when your unpacked extension lives outside the default project output. * Use `--browser` to verify behavior across targets before packaging. ## Next steps * Build and launch in one step with [`start`](/docs/commands/start). * Generate production artifacts with [`build`](/docs/commands/build). * Configure shared defaults in [`extension.config.js`](/docs/features/extension-configuration). * Review configuration env loading behavior in [Environment variables](/docs/features/environment-variables#how-it-works). # Publish command for shareable build URLs Source: https://extension.js.org/docs/commands/publish Turn a project on extension.dev into a shareable URL with the Extension.js publish command. Requires an access token and prints the share link. Ask [extension.dev](https://docs.extension.dev?utm_source=extension-js-org\&utm_medium=sponsor\&utm_campaign=docs-seam) for a shareable URL to a project you already have there. `publish` is a thin client. It does not compile, package, or upload anything. It sends one authenticated request to the platform and prints the URL the platform answers with. ## When to use `publish` * Sending a reviewer a link to a build instead of a zip file. * Wiring a share link into CI after `build` produced the artifacts. * Pinning a share link to one specific build rather than the project's latest. `publish` resolves a project that already exists on extension.dev, so it needs a build the platform recorded. To send someone the build sitting in your own `dist/` right now, upload that build instead: [Share an unpublished build for review](https://docs.extension.dev/share/unpublished-build-for-review?utm_source=extension-js-org\&utm_medium=sponsor\&utm_campaign=docs-seam). > [!NOTE] > > `publish` talks to the extension.dev platform, which is a separate product > from Extension.js. The Extension.js commands that run on your machine > (`create`, `dev`, `build`, `preview`, `start`) never need an account. > `publish` does. ## Usage ```bash npm theme={null} extension publish [project-path] [options] ``` ```bash pnpm theme={null} extension publish [project-path] [options] ``` ```bash yarn theme={null} extension publish [project-path] [options] ``` ```bash bun theme={null} extension publish [project-path] [options] ``` ```bash deno theme={null} extension publish [project-path] [options] ``` The project that gets published is whatever your token is scoped to. The path argument does not upload anything. It names the local directory whose project name the scope check below compares against. ## Token requirement `publish` refuses to run without an access token. It looks in three places, in this order: 1. `--token ` on the command line. 2. `EXTENSION_DEV_TOKEN` in the environment (preferred for CI). 3. The stored device login that `npx @extension.dev/mcp login` writes. Without any of them, the command exits with code `1` before any network call happens, and prints this to stderr: ```plaintext theme={null} No token. Publishing needs an extension.dev access token. Get one: https://docs.extension.dev/tools/publish Pass --token, set EXTENSION_DEV_TOKEN, or run npx @extension.dev/mcp login. ``` Create a token from the extension.dev dashboard or the project access-tokens API, documented in [Access tokens](https://docs.extension.dev/tools/access-tokens?utm_source=extension-js-org\&utm_medium=sponsor\&utm_campaign=docs-seam). ## Scope checks A stored device login is scoped to one project. Publishing from an unrelated directory would mint a share link for that project without naming it anywhere obvious. `publish` treats that mismatch as a refusal, not a warning: * When the directory's project name does not match the stored login's project, the command refuses and names both. * Pass `--project ` to publish the login's project on purpose from anywhere. * Passing `--project` with a slug that does not match the stored login also refuses. * A `--token` or `EXTENSION_DEV_TOKEN` token skips the stored-login comparison entirely. The local project name comes from `package.json`, then `manifest.json`, then `src/manifest.json`, then the folder name. ## Arguments and flags | Flag | What it does | Default | | - | - | - | | `[project-path]` | Directory whose project name the scope check reads. Not uploaded. | `process.cwd()` | | `--token ` | extension.dev access token. | `EXTENSION_DEV_TOKEN`, then stored login | | `--api ` | Platform base URL. Useful for self-hosted or staging endpoints. | `EXTENSION_DEV_API_URL`, then platform URL | | `--ttl ` | Share-link lifetime in hours, from 1 to 168. Private projects only. | `24` | | `--build-sha ` | Pin the share URL to a specific build instead of the latest. | latest build | | `--project ` | Name the project this publish is for, when it is not the directory you are in. | unset | | `--output ` | Output format. `json` prints the full platform response. | `pretty` | ## What it prints Pretty output is a single line, the share URL, so it pipes cleanly: ```bash theme={null} extension publish # https://.extension.dev/ ``` `--output json` prints one envelope. The platform response sits in `value`, and it carries more than the URL: ```json theme={null} { "schema": 1, "ok": true, "command": "publish", "status": "published", "value": { "shareUrl": "https://.extension.dev/?share=", "visibility": "private", "token": "", "expiresAt": "2026-01-01T00:00:00.000Z", "ttlHours": 24, "project": "", "tokenSource": "stored-login" }, "error": null, "warnings": [] } ``` A public project answers with `value.shareUrl` and `value.visibility` only. There is no token to carry. With `--build-sha`, the URL points at that build instead of the project overview: `https://.extension.dev//builds/`. ## Public and private projects A project is either public or private. `publish` only reads that setting and never changes it. The platform decides what kind of link you get: | Project visibility | What comes back | | - | - | | Public | The project's own address, with no token. `--ttl` is ignored because nothing expires. | | Private | That same address plus `?share=`, which stops working after `--ttl` hours. | Both answers point at the same page. Visibility decides whether a token is attached, not which address you get. ## Pinning to a build `--build-sha` links to one build instead of the project's latest. The platform verifies the sha against the project's build index and answers with a `404` and an `UNKNOWN_BUILD` code when no completed build matches, so a typo fails loudly instead of producing a link to the wrong artifact. ```bash npm theme={null} extension publish --build-sha=9fceb02 ``` ```bash pnpm theme={null} extension publish --build-sha=9fceb02 ``` ```bash yarn theme={null} extension publish --build-sha=9fceb02 ``` ```bash bun theme={null} extension publish --build-sha=9fceb02 ``` ```bash deno theme={null} extension publish --build-sha=9fceb02 ``` ## Examples ### Publishing from CI ```bash theme={null} EXTENSION_DEV_TOKEN=$EXTENSION_DEV_TOKEN npx extension@latest build --browser=chrome --zip SHARE_URL=$(EXTENSION_DEV_TOKEN=$EXTENSION_DEV_TOKEN extension publish) echo "Review build: $SHARE_URL" ``` ### A short-lived link for one reviewer ```bash npm theme={null} extension publish --ttl=4 ``` ```bash pnpm theme={null} extension publish --ttl=4 ``` ```bash yarn theme={null} extension publish --ttl=4 ``` ```bash bun theme={null} extension publish --ttl=4 ``` ```bash deno theme={null} extension publish --ttl=4 ``` ## Behavior notes * `publish` never compiles. Run [`build`](/docs/commands/build) first when you want the link to point at fresh output. * Every failure path exits with code `1`: a missing token, an unreachable platform, or any non-2xx response, which is printed as `publish failed (): `. * `--api` accepts a base URL with or without a trailing slash. The command appends `/api/cli/publish` itself. * `--ttl` is clamped by the platform to the 1 to 168 hour range. * The `?share=` token this command returns is not the 30 day revocable preview link. That link comes from a different verb, which uploads the build; `publish` uploads nothing. See [the platform's publish page](https://docs.extension.dev/tools/publish?utm_source=extension-js-org\&utm_medium=sponsor\&utm_campaign=docs-seam). ## Next steps * Produce the artifacts to share with [`build`](/docs/commands/build). * Validate the artifacts locally first with [`preview`](/docs/commands/preview). * Hand someone an unpublished build behind a link with no zip and no install, in [Share an unpublished build for review](https://docs.extension.dev/share/unpublished-build-for-review?utm_source=extension-js-org\&utm_medium=sponsor\&utm_campaign=docs-seam). * Read how builds are recorded in [Builds](https://docs.extension.dev/builds/overview?utm_source=extension-js-org\&utm_medium=sponsor\&utm_campaign=docs-seam). # Reload command for extension contexts Source: https://extension.js.org/docs/commands/reload Reload the background worker, a content script tab, or a page of a running Extension.js dev session on demand, from the terminal or a script. Reload a running extension or tab on demand. The [`dev`](/docs/commands/dev) session already reloads automatically when files change. `reload` is for the cases automatic reload cannot see: state you mutated by hand, a wedged service worker, or a test that needs a clean context between runs. The session must run with the control channel unlocked: start it with `extension dev --allow-control`. A refusal names the missing flag. ## When to use `reload` * The background worker holds bad in-memory state and you want a clean restart. * A script seeded storage or triggered a flow and needs a fresh context afterward. * You changed something outside the watcher's view and want to force a re-read. ## Usage ```bash npm theme={null} extension reload [project-path] [options] ``` ```bash pnpm theme={null} extension reload [project-path] [options] ``` ```bash yarn theme={null} extension reload [project-path] [options] ``` ```bash bun theme={null} extension reload [project-path] [options] ``` ```bash deno theme={null} extension reload [project-path] [options] ``` ## Arguments and flags | Flag | What it does | Default | | - | - | - | | `[project-path]` | Path to the extension project root. | `process.cwd()` | | `--context ` | What to reload: `background`, `content`, or `page`. | `background` | | `--url ` | For `content`/`page`: the document to target, resolved to its tab. | unset | | `--tab ` | For `content`/`page`: a specific tab. Without it, the `--url` match wins, else the active tab. | active tab | | `--browser ` | Which session to target (`chrome`, `chromium`, `edge`, `firefox`). | `chromium` | | `--timeout ` | Command timeout in milliseconds. | `5000` | | `--output ` | Output format (`json` wraps the result in the schema-1 envelope). | `pretty` | ## What each context reloads * `background` restarts the extension itself, which restarts the service worker and re-reads the manifest. * `content` reloads the tab that hosts the targeted content script, so the script re-injects. * `page` reloads the targeted tab as a plain page reload. Find numeric tab ids with [`inspect --list-tabs`](/docs/commands/inspect#the-discovery-loop) when the active tab is not the one you want. ## Failure modes * No session for the browser: `E_SESSION_NOT_FOUND`, with the exact `extension dev --allow-control` command to run. * From the release after 4.1.39, a session that has ended answers `E_SESSION_NOT_FOUND` too, and the message prints the command that starts it again. See [When the session has ended](/docs/debugging#when-the-session-has-ended). * Session running without `--allow-control`: the connection is refused and the error names the flag. * A `--tab` id that no longer exists: `E_TARGET_NOT_FOUND`. * The call outlived `--timeout`: `E_TIMEOUT`. The exit code is `0` on success and `1` on any failure. Machine consumers should read the envelope from `--output json` (see [Result envelope](/docs/contracts/result-envelope)). ## Next steps * Understand what automatic reload already covers in [Reload and HMR](/docs/features/reload-and-hmr). * Verify the reloaded context came back clean with [`logs`](/docs/commands/logs) or [`inspect`](/docs/commands/inspect). * Diagnose a session that refuses the call with [`doctor`](/docs/commands/doctor). * Read the wider debugging workflow in [Debugging](/docs/debugging). # Start command for build-and-launch workflow Source: https://extension.js.org/docs/commands/start Run a production build and immediately launch the extension in the browser with one command. Combines build and preview into a single step. Use `start` when you want a production build and immediate browser launch in one command. The `start` command runs a production build first, then launches the built extension using the same flow as the `preview` command. ## When to use `start` * Manually validating production behavior right after compilation. * Reproducing runtime differences between watch mode and production output. * Running a production-like check locally without a separate `build` then `preview` step. ## Start command capabilities | Capability | What it gives you | | - | - | | Build + launch workflow | Run production compile and browser launch in one step | | Target selection | Start directly in selected browser or engine target | | Runner control | Skip browser launch when you only need build verification | | Production-like validation | Check real compiled output instead of watch-mode state | ## How it differs from other commands * `dev`: dev server + hot module replacement (HMR)/watch mode * `build`: production build only * `preview`: launch an existing built extension without building * `start`: `build` + `preview` in sequence ## Usage ```bash npm theme={null} extension start [path-or-url] [options] ``` ```bash pnpm theme={null} extension start [path-or-url] [options] ``` ```bash yarn theme={null} extension start [path-or-url] [options] ``` ```bash bun theme={null} extension start [path-or-url] [options] ``` ```bash deno theme={null} extension start [path-or-url] [options] ``` If you omit the path, the command uses the current working folder. ## Arguments and flags | Flag | Alias | What it does | Default | | - | - | - | - | | `[path or url]` | - | Extension path or remote URL. | `process.cwd()` | | `--browser ` | - | Browser/engine target. | `commands.start.browser`, else `chromium` | | `--profile ` | - | Browser profile path or boolean profile mode. | fresh profile | | `--chromium-binary ` | - | Custom Chromium-family binary path. | managed install, then system install | | `--gecko-binary ` | `--firefox-binary` | Custom Gecko-family binary path. | managed install, then system install | | `--polyfill [boolean]` | - | Enable `browser.*` API compatibility polyfill for Chromium targets. | `true` | | `--no-polyfill` | - | Disable the cross-browser polyfill. | polyfill enabled | | `--starting-url ` | - | Starting URL in launched browser. | unset | | `--no-open` | - | Launch the browser, but do not open a tab for your extension. The browser still starts and loads it. See [stop the browser from launching](#stop-the-browser-from-launching). | a tab opens on launch | | `--no-browser` | - | Stop the browser from launching. The build still runs. See [stop the browser from launching](#stop-the-browser-from-launching). | browser launch enabled | | `--wait [boolean]` | - | Wait for `dist/extension-js//ready.json` and exit. | disabled | | `--wait-timeout ` | - | Timeout for `--wait` mode. | `60000` | | `--output ` | - | Result format. `json` prints a schema-1 envelope on stdout. | `pretty` | | `--port ` | - | Runner/devtools port when runner is enabled. Use `0` for OS-assigned port. | `8080` | | `--host ` | - | Host to bind the dev server to. Use `0.0.0.0` for Docker/dev containers. | `127.0.0.1` | | `--public-host ` | - | Accepted for parity with `dev`, so a script that shares flags between the two is not refused. `start` serves nothing, so the value has no effect. | unset | | `--extensions ` | - | Comma-separated companion extensions or store URLs. | unset | | `--install [boolean]` | - | Internal flag. Install project dependencies when missing. | command behavior default | | `--allow-control` | - | Open the agent-bridge control channel on the production run for the act verbs (`storage`, `reload`, `open`). The browser loads a copy of the build with the control producer added, `dist/` is unchanged. | disabled | | `--allow-eval` | - | Also enable `extension eval` on the production run. Implies `--allow-control` and writes a `0600` session token. | disabled | | `--enable-extension` | - | Turn the extension on in Safari Settings through macOS Accessibility. Safari targets only, and `start` has no Safari path yet. | off | | `--debug` | - | Enable maintainer diagnostics. | disabled | On Firefox, `--starting-url` opens after the add-on installs, so your `document_start` content scripts run on that page. From the release after 4.1.39, it no longer replaces a tab that your extension opened. Two deprecated aliases are hidden from `--help` but still work: * `--wait-format ` maps onto `--output` and warns once on stderr. Migrate scripts to `--output`. * `--author` and `--author-mode` map onto `--debug`. ## Browser support `start` has no Safari path. Passing `--browser safari` (or `webkit-based`) exits with `E_COMMAND_UNSUPPORTED_FOR_TARGET`. The reason is measured. Safari's WebDriver route does load an unpacked folder, and the background even runs, but Safari grants the extension zero host origins. Content scripts never inject, and no API call can grant the access afterwards. Use [`dev`](/docs/commands/dev) or [`build`](/docs/commands/build) for Safari targets. `start` also refuses `chromium-emulator` and exits with `E_UNSUPPORTED_BROWSER`. The emulated Chromium page reads your build from the dev server, which `start` does not run. Use [`dev`](/docs/commands/dev#emulated-chromium) for that target. ## Automation metadata `start` writes readiness metadata to: * `dist/extension-js//ready.json` This is useful for automation when using `--no-browser`: * Wait for `status: "ready"` before launching external runners. * Handle `status: "error"` as a deterministic failure signal. * Use `runId` and `startedAt` to correlate a specific runtime session. From the release after 4.1.39, with `--allow-control` or `--allow-eval`, the status stays `starting` until the extension's background connects or 10 seconds pass. Read `executorAttachedAt` to know that an act verb can run. See [the ready.json contract](/docs/contracts/ready-json#sessions-that-take-act-verbs-hold-ready). From the release after 4.1.39, a refusal from such a session names `extension start` as the command to restart. A build with no background script or service worker cannot be controlled: the session warns at startup, and every act verb answers that the build has no background. See [Refusals on a start or preview session](/docs/debugging#refusals-on-a-start-or-preview-session). After the session ends, an act verb says so and prints the `extension start` command that starts it again. See [When the session has ended](/docs/debugging#when-the-session-has-ended). ### Stop the browser from launching Two flags sound alike and do different things: | You want | Flag | What happens | | - | - | - | | No browser at all | `--no-browser` | No browser process starts. The production build still runs. | | A browser, but no tab opened for your extension | `--no-open` | The browser starts and loads your extension. No tab is opened for it. | ```bash theme={null} # Stop the browser launch. The production build still runs. npx extension@latest start --no-browser # Launch the browser without opening a tab for the extension. npx extension@latest start --no-open ``` `--no-browser` also has a config form, `commands.start.noBrowser: true`, and an environment form, `EXTENSION_CLI_NO_BROWSER=1`. `dev`, `start`, and `preview` all accept both flags. ### `--no-browser` and readiness synchronization `--no-browser` only disables browser launch. It does not block external runners until the production build finishes. For production-oriented Playwright, continuous integration (CI), and AI workflows: 1. Run `extension start --no-browser` as the producer process. 2. Run `extension start --wait --browser=` as the readiness gate. 3. Launch external browser automation only after `status: "ready"`. `--wait` exits non-zero on `error`/timeout and ignores stale contracts from dead processes (`pid` no longer alive). Because `start` can finish quickly, a contract from a completed run still counts when its timestamp is within a 60 second window. `--wait` requires a local project path. Passing a remote URL exits with `E_ARGS`. Passing both `--wait` and `--no-browser` in the same invocation exits with `E_INVALID_OPTION`, because `--wait` only reads a contract that another process writes. Run them as two processes, as in the steps above. ### Machine output with `--output json` `--output json` prints schema-1 envelopes on stdout, one JSON object per line: * A plain `start` run prints one `status: "started"` frame once the build finished and the browser launched. It carries the project path, browser list, `pid`, and `port: null`, because a run-only session binds no port. A run that fails prints only its failure frame, never a `started` frame before it. * A `start --wait` run prints one `status: "ready"` frame on success. Its `value.results` array carries the full ready contract per browser. * A `start --wait` run that reads a contract in `error` status prints one `ok: false` frame that names the cause, for example `E_BROWSER_LAUNCH` when the browser never started or `E_BROWSER_EXITED` when it exited. See [the ready.json contract](/docs/contracts/ready-json) for the full list. * A failed build prints one `ok: false` frame with `status: "build-failed"` before the process exits `1`. A compile error carries `error.code: "E_COMPILE"`. A missing project folder carries `E_PROJECT_NOT_FOUND`, a folder with no manifest carries `E_MANIFEST_NOT_FOUND`, and a manifest that does not parse carries `E_MANIFEST_INVALID`. A config file that fails to load carries `E_CONFIG_LOAD`, and a remote URL that gives no usable archive carries `E_REMOTE_ZIP_INVALID`, `E_REMOTE_FETCH_TIMEOUT`, `E_REMOTE_ACCESS_DENIED`, or `E_REMOTE_DOWNLOAD`. * A bad `--chromium-binary` or `--gecko-binary` pin prints one `ok: false` frame with `status: "usage"` and `error.code: "E_BROWSER_BINARY_INVALID"`. That covers a path that does not exist, a file that is not executable, and a binary that does not answer its version probe within 10 seconds. The command ends and leaves nothing running. * A browser that cannot start prints one `ok: false` frame with `status: "failed"`. The code is `E_BROWSER_LAUNCH` when the binary is executable but the system cannot start it or Firefox exits before its debugger answers, and `E_BROWSER_CONNECT` when Firefox runs but its debugger never answers. ## Logging flags These flags are experimental and may change between minor releases. | Flag | What it does | Default | | - | - | - | | `--logs ` | Minimum log level. | `off` | | `--log-context ` | Context filter (`background`, `content`, `page`, `popup`, `options`, `sidebar`, `devtools`, `newtab`, `history`, `bookmarks`). | `all` | | `--log-format ` | Logger output format. | `pretty` | | `--no-log-timestamps` | Disable timestamps in pretty mode. | timestamps enabled | | `--no-log-color` | Disable color in pretty mode. | color enabled | | `--log-url ` | Filter log events by URL substring/regex. | unset | | `--log-tab ` | Filter log events by tab ID. | unset | ## Shared global options Also supports [Global flags](/docs/workflows/global-flags). ## Examples ### Start with default browser [Extension.js: extension start](https://www.youtube-nocookie.com/embed/voPbTvrVU9M?rel=0) ```bash npm theme={null} npx extension@latest start ``` ```bash pnpm theme={null} pnpx extension@latest start ``` ```bash yarn theme={null} yarn dlx extension@latest start ``` ```bash bun theme={null} bunx extension@latest start ``` ```bash deno theme={null} deno run -A npm:extension@latest start ``` ### Start in Firefox ```bash npm theme={null} npx extension@latest start --browser firefox ``` ```bash pnpm theme={null} pnpx extension@latest start --browser firefox ``` ```bash yarn theme={null} yarn dlx extension@latest start --browser firefox ``` ```bash bun theme={null} bunx extension@latest start --browser firefox ``` ```bash deno theme={null} deno run -A npm:extension@latest start --browser firefox ``` ### Build and skip browser launch ```bash npm theme={null} npx extension@latest start --no-browser ``` ```bash pnpm theme={null} pnpx extension@latest start --no-browser ``` ```bash yarn theme={null} yarn dlx extension@latest start --no-browser ``` ```bash bun theme={null} bunx extension@latest start --no-browser ``` ```bash deno theme={null} deno run -A npm:extension@latest start --no-browser ``` ## Behavior notes * `start` does not run a dev server and does not provide hot module replacement (HMR) or watch mode. * `start` is production-mode oriented. Use `dev` for iterative local development. * For machine consumers, parse `dist/extension-js//ready.json` instead of terminal text. ## Next steps * Iterate quickly with [`dev`](/docs/commands/dev). * Launch existing build output with [`preview`](/docs/commands/preview). # Storage command for reading and writing data Source: https://extension.js.org/docs/commands/storage Read and write chrome.storage areas of a running Extension.js dev session from the terminal, with JSON values and per-area targeting. Read and write the extension's `chrome.storage` areas from the terminal. `storage` talks to a running dev session and runs the storage call inside the extension itself, so you see exactly what your code sees. No DevTools, no temporary `console.log`. The session must run with the control channel unlocked: start it with `extension dev --allow-control`. A refusal names the missing flag. ## When to use `storage` * You want to check what your extension persisted without wiring up a debug UI. * A test or agent needs to seed storage state before exercising a flow. * You want to flip a stored feature flag in a live session and watch the effect. ## Usage ```bash npm theme={null} extension storage [project-path] [options] ``` ```bash pnpm theme={null} extension storage [project-path] [options] ``` ```bash yarn theme={null} extension storage [project-path] [options] ``` ```bash bun theme={null} extension storage [project-path] [options] ``` ```bash deno theme={null} extension storage [project-path] [options] ``` Read the whole `local` area, then one key, then write a value: ```bash theme={null} extension storage get extension storage get --key settings extension storage set --key settings --value '{"theme": "dark"}' ``` ## Arguments and flags | Flag | What it does | Default | | - | - | - | | `` | `get` or `set`. | required | | `[project-path]` | Path to the extension project root. | `process.cwd()` | | `--area ` | Storage area (`local`, `sync`, `session`, `managed`). | `local` | | `--key ` | Key to get or set. `get` without a key returns the whole area. | unset | | `--value ` | Value to write with `set`. Parsed as JSON first, kept as a raw string if that fails. | required for `set` | | `--context ` | Context that runs the call (`background`, `popup`, `options`, `sidebar`, `content`). | `background` | | `--browser ` | Which session to target (`chrome`, `chromium`, `edge`, `firefox`). | `chromium` | | `--timeout ` | Command timeout in milliseconds. | `5000` | | `--output ` | Output format (`json` wraps the result in the schema-1 envelope). | `pretty` | ## How values are parsed `--value` is parsed as JSON, so `'{"theme": "dark"}'`, `'42'`, and `'true'` arrive typed. Input that is not valid JSON falls back to a raw string, so `--value hello` stores the string `"hello"` without extra quoting. `set` requires both `--key` and `--value`. Leaving either out fails with `E_ARGS` before any connection is made. Any action other than `get` or `set` fails the same way. ## Failure modes * No session for the browser: `E_SESSION_NOT_FOUND`, with the exact `extension dev --allow-control` command to run. * From the release after 4.1.39, a session that has ended answers `E_SESSION_NOT_FOUND` too, and the message prints the command that starts it again. See [When the session has ended](/docs/debugging#when-the-session-has-ended). * Session running without `--allow-control`: the connection is refused and the error names the flag. * The storage call threw inside the extension (for example, writing to the read-only `managed` area): `E_STORAGE`. * The call outlived `--timeout`: `E_TIMEOUT`. The exit code is `0` on success and `1` on any failure. Machine consumers should read the envelope from `--output json` (see [Result envelope](/docs/contracts/result-envelope)). ## Next steps * Run arbitrary expressions in the same session with [`eval`](/docs/commands/eval). * Restart the background worker after seeding state with [`reload`](/docs/commands/reload). * Diagnose a session that refuses the call with [`doctor`](/docs/commands/doctor). * Read the wider debugging workflow in [Debugging](/docs/debugging). # Uninstall command to remove managed browsers Source: https://extension.js.org/docs/commands/uninstall Remove managed browser runtimes from the Extension.js cache. Only affects browsers installed by Extension.js, not your system browsers. Use `uninstall` to remove managed browser runtimes from the Extension.js cache. > [!WARNING] > > `uninstall` removes browser runtimes that Extension.js downloaded into its > managed cache. It never removes your system browser, and it never removes an > extension installed in a browser. To remove a development extension, stop the > `dev` session. The extension was loaded into a managed browser profile, not > into your own browser profile. ## When to use `uninstall` * You want to reclaim disk space from managed browsers you no longer need. * You are resetting a managed browser install to force a fresh download on next `install`. * You are cleaning up continuous integration (CI) caches or switching browser targets. ## Canonical usage For a single browser, use the positional form: ```bash npm theme={null} extension uninstall ``` ```bash pnpm theme={null} extension uninstall ``` ```bash yarn theme={null} extension uninstall ``` ```bash bun theme={null} extension uninstall ``` ```bash deno theme={null} extension uninstall ``` Use `--all` to remove every managed browser target. ## Usage ```bash npm theme={null} extension uninstall [browser-name] [options] ``` ```bash pnpm theme={null} extension uninstall [browser-name] [options] ``` ```bash yarn theme={null} extension uninstall [browser-name] [options] ``` ```bash bun theme={null} extension uninstall [browser-name] [options] ``` ```bash deno theme={null} extension uninstall [browser-name] [options] ``` ## Arguments and flags | Flag / argument | What it does | Default | | - | - | - | | `[browser-name]` | Remove a single managed browser such as `chrome`, `chromium`, `edge`, or `firefox` | unset | | `--browser ` | Explicit flag form of the browser argument | unset | | `--all` | Remove all managed browser runtimes from the Extension.js cache | disabled | | `--where` | Print the resolved cache root, or browser-specific managed paths | disabled | | `--output ` | Result format. `json` prints a schema-1 envelope on stdout | `pretty` | `--all` removes the same managed set that `install --browser all` creates: `chrome`, `chromium`, `edge`, and `firefox`. ## Machine output with `--output json` `--output json` prints one schema-1 envelope on stdout: * A successful removal prints a `status: "uninstalled"` frame naming the target in `value`. * `--where` prints a `status: "located"` frame with the resolved paths in `value.paths`. * A failed removal prints `ok: false` with `error.code: "E_BROWSER_UNINSTALL"` before the process exits `1`. ## Examples ### Remove managed Chrome for Testing ```bash theme={null} extension uninstall chrome ``` ### Remove all managed browsers ```bash theme={null} extension uninstall --all ``` ### Show the managed uninstall path for Firefox ```bash theme={null} extension uninstall firefox --where ``` ## Best practices * **Use `--all` in CI teardown** to clean up managed browsers after test runs. * **Use `--where` first** to confirm what will be removed before scripting bulk uninstalls. ## Behavior notes * If you set `EXT_BROWSERS_CACHE_DIR`, uninstall uses that custom cache root. ## Next steps * Reinstall managed browsers with [`install`](/docs/commands/install). * Review browser targeting with [`dev`](/docs/commands/dev) and [`start`](/docs/commands/start). * Learn about [Running other browsers](/docs/browsers/running-other-browsers) with custom binary paths. # Extension.js vs CRXJS Source: https://extension.js.org/docs/compare/extension-js-vs-crxjs Compare Extension.js and CRXJS for browser extension development: a bundler-owning framework vs a Vite plugin, browser targets, dev loop, and packaging. Extension.js and [CRXJS](https://crxjs.dev) both turn a `manifest.json` and modern source into a working extension. Extension.js is a CLI framework that owns its bundler. CRXJS is a plugin that adds extension output to a Vite setup you own. This page is a factual comparison so you can choose based on your project. ## Which should you choose? > [card] Choose Extension.js if… > > * You want one CLI that opens the browser, reloads on save, builds per browser, and zips for the stores. > * You ship to Chrome, Edge, Firefox, and Safari from one `manifest.json`. > * You want no bundler config in your project. > [card] Choose CRXJS if… > > * You already have a Vite app and want extension output added to it. > * You depend on Vite plugins and want to keep them. > * You are fine loading the unpacked build in the browser yourself. ## At a glance | Dimension | Extension.js | CRXJS | | - | - | - | | What it is | CLI framework, [Rspack](/docs/features/rspack-configuration) is an internal detail | Vite plugin inside your own `vite.config` | | Manifest | One `manifest.json`, browser-prefixed keys filtered per build | `manifest.json`, or `defineManifest` in a config file | | Browsers | Chrome, Edge, Firefox, Safari (macOS, through Xcode), Chromium and Gecko binaries | Chrome by default, Firefox through the `browser` option | | Dev loop | Opens a managed browser with the extension loaded and reloads on save | HMR for pages and content scripts, you load the build unpacked | | Build output | `dist/`, with `--zip` per store | Vite's output folder, you zip it yourself | | Customization | Rspack config hook in `extension.config.js` | Any Vite plugin | | Vite versions | Not applicable | Vite 3 to 8 | | Latest release | 4.1.39 (November 2026) | 3.0.0 (September 2026) | ## Mental model **Extension.js owns the bundler.** You write a `manifest.json` and reference real files. The CLI compiles them, filters the manifest for each browser, and packages the result. You never configure the bundler, and bundler upgrades are the framework's job. **CRXJS lives inside your bundler.** You add `crx({ manifest })` to `vite.config`, and Vite builds the extension next to the rest of your app. You keep full control of Vite and every Vite plugin. Each Vite major needs CRXJS compatibility work, which is why the [Vite 8 fileName error](/docs/migrate/crxjs-content-script-filename-undefined) existed for a while. ## Dev loop ### Extension.js ```bash theme={null} npx extension@latest dev --browser=chrome,firefox ``` The CLI opens each browser with a fresh profile and the extension loaded. A save reloads the right surface: HMR for pages, a targeted reload for content scripts and the service worker. ### CRXJS ```bash theme={null} npm run dev ``` Vite starts its dev server and writes the extension to the output folder. You load that folder unpacked in the browser once, then HMR updates pages and content scripts. ## Cross-browser builds * **Extension.js** builds every browser from one source with `--browser`. * Browser differences go in [browser-prefixed manifest fields](/docs/features/browser-specific-fields), such as `chrome:` and `firefox:`. * **CRXJS** builds one target per run, and `browser: 'firefox'` in the plugin options gives a Firefox build. * The CRXJS docs have no Safari guide. ## Packaging ```bash theme={null} npx extension@latest build --browser=chrome,firefox,edge --zip ``` Extension.js writes `dist/` and a zip per browser next to it. With CRXJS, you zip Vite's output folder with your own script or tool. ## When to migrate Move from CRXJS to Extension.js when you want the CLI to launch browsers, build several browsers in one run, or ship to Safari. Your components, `chrome.*` calls, and styles carry over. [Migrate from CRXJS](/docs/migrate/from-crxjs) walks through it step by step. ## See also * [Browser extension framework comparison](/docs/compare) * [Extension.js vs WXT](/docs/compare/extension-js-vs-wxt) * [Cross-browser compatibility](/docs/features/cross-browser-compatibility) # Extension.js vs Plasmo Source: https://extension.js.org/docs/compare/extension-js-vs-plasmo Compare Extension.js and Plasmo for browser extension development: manifest model, bundler, browser targets, dev loop, packaging, and maintenance status. Extension.js and [Plasmo](https://www.plasmo.com) both compile a browser extension from modern source, reload it while you work, and package it for the stores. They differ in where the manifest lives, which bundler does the work, and how actively each one ships. This page is a factual comparison so you can choose based on your project, not marketing copy. ## TL;DR: which should you choose? > [card] Choose Extension.js if… > > * You want the **`manifest.json` as the source of truth**, not generated from file names. > * You want the CLI to launch the browser and load the extension for you. > * You target Chrome, Edge, Firefox, and Safari from one tree, with per-browser `dist/` output. > * You want a bundler that still receives releases, and docs that your assistant can read through a docs MCP endpoint and `llms.txt` ([details](/docs/ai-access)). > [card] Choose Plasmo if… > > * You prefer **file-system convention** (`popup.tsx`, `contents/`) over an explicit manifest. > * You rely on **CSUI**, which mounts a React, Svelte, or Vue component into a page inside a shadow root for you. > * You use `@plasmohq/storage` and `@plasmohq/messaging`, and your extension already works on the pinned toolchain. The rest of this page backs up that summary, dimension by dimension. ## At a glance | Dimension | Extension.js | Plasmo | | - | - | - | | Bundler | [Rspack](/docs/features/rspack-configuration) (Rust-based) | Parcel, pinned at `@parcel/core` 2.9.3 in the 0.90.5 CLI | | Manifest | One `manifest.json`, browser-prefixed keys filtered at compile time | Generated from file conventions plus a `manifest` field in `package.json` | | Entrypoints | Files referenced from `manifest.json` | `popup.tsx`, `options.tsx`, `newtab.tsx`, `background.ts`, `contents/*` | | Browser targets | Chrome, Edge, Firefox, Safari (macOS, through Xcode), Chromium, Gecko, custom binaries | `chrome-mv3` (default), `firefox-mv2`, `firefox-mv3` (experimental) | | Other Chromium browsers | Brave, Opera, Vivaldi, Yandex, and any binary through `--chromium-binary` | "Should work" as Chromium builds, loaded by hand | | Safari | `extension build --browser=safari` converts and runs `xcodebuild` | `safari-mv3` target, then you run `safari-web-extension-converter` yourself | | Manifest V2 | Not supported as a primary target | `firefox-mv2` target | | Dev loop | Launches the browser on a fresh profile and loads the build | Live-reloading server, you load `build/chrome-mv3-dev` unpacked by hand | | Reload model | HMR for popup/options/devtools, classified reload for content scripts and the worker | Live reload plus React HMR | | Output | `dist/` | `build/-dev` and `build/-prod` | | Packaging | `extension build --zip`, plus `--zip-source` and `--zip-filename` | `plasmo package`, or `plasmo build --zip` | | Store submission | Not part of the CLI, `extension publish` is a share link | Browser Platform Publisher, a GitHub Action with a `keys.json` secret | | Env vars | `EXTENSION_PUBLIC_*` | `PLASMO_PUBLIC_*`, with `.env.` overrides | | Templates | 59 in the catalog, starters: init, javascript, typescript, react, preact, vue, svelte | React and TypeScript first class, Svelte and Vue optional | | AI surfaces | Docs MCP endpoint + `llms.txt` ([details](/docs/ai-access)) | None documented | ## Mental model **Extension.js stays close to the platform.** You author a `manifest.json` and reference real files. The CLI compiles, filters per browser, and ships. If you already understand how a browser extension is structured, the framework gets out of your way. **Plasmo abstracts the platform.** A file named `popup.tsx` becomes the popup. A file under `contents/` becomes a content script, and its `matches` come from an exported `config` object. Plasmo's own docs describe it as "like Next.js for browser extensions". The manifest is generated under the hood from your source files and from the `manifest` field in `package.json`. Neither approach is universally better. The choice depends on whether you want to **see** your manifest or **declare** your manifest. ## CLI surface ### Extension.js ```bash theme={null} npx extension@latest dev --browser=chrome,firefox npx extension@latest build --browser=chrome,firefox --zip npx extension@latest dev https://github.com/user/repo/tree/main/path ``` `extension dev` launches the browser on a temporary profile and loads the build. The argument can be a local path, a GitHub URL, or a ZIP archive. See [Get started immediately](/docs/getting-started/immediately). ### Plasmo ```bash theme={null} plasmo dev plasmo dev --target=firefox-mv2 plasmo build --target=chrome-mv3 plasmo package ``` `plasmo dev` writes `build/chrome-mv3-dev` and starts a live-reloading server. Loading that folder into the browser is a manual step: the Plasmo docs say "We plan to automate this in the future." Every browser and manifest pair is one `--target` value. ## Cross-browser strategy Both frameworks ship one codebase to several browsers, with different mechanics: * **Extension.js** uses [browser-prefixed manifest fields](/docs/features/browser-specific-fields) (`chrome:`, `firefox:`, `gecko:`, and so on) inside one `manifest.json`. The unprefixed keys apply everywhere, and prefixed keys land only in matching builds. One run with `--browser=chrome,firefox` writes `dist/chrome` and `dist/firefox`. * **Plasmo** builds one target per run. Browser differences live in environment variables: a `.env.firefox` file, `process.env.PLASMO_BROWSER` in code, and env placeholders inside the `manifest` overrides. A placeholder that resolves to nothing removes the field from the generated manifest. Plasmo's officially supported targets are `chrome-mv3`, `firefox-mv2`, and the experimental `firefox-mv3`. Its FAQ says Edge, Brave, and Opera "should work" because they are Chromium. Safari needs the `safari-mv3` target plus a manual run of Apple's converter. Extension.js names each of those browsers as a `--browser` value, and [the Safari build](/docs/browsers/safari) runs the converter and `xcodebuild` for you. ## Where Plasmo is ahead Be honest about this before you move: * **CSUI.** Export a React, Svelte 3, or Vue 3 component from a content script. Plasmo mounts it in a shadow root, isolated from the host page's styles. In Extension.js you write the container and the shadow root yourself, as shown in [Content scripts](/docs/implementation-guide/content-scripts). * **Store submission from the repo.** Plasmo documents a GitHub Action, Browser Platform Publisher, that reads a `keys.json` secret and uploads to the stores. Extension.js builds the archives ([Package an extension for store upload](/docs/publishing/package-for-the-stores)). The upload is left to your CI against each store's API. The `extension publish` command produces a share link on extension.dev, not a store submission. * **Bundled helper libraries.** `@plasmohq/storage` and `@plasmohq/messaging` wrap `chrome.storage` and `chrome.runtime` messaging. Extension.js has no equivalent packages. You call the browser APIs directly, which is also why `@plasmohq/storage` keeps working after a migration. ## Maintenance status Check the signals yourself before you decide. These values come from npm and the GitHub API on 5 October 2026. | Signal | Plasmo | Extension.js | | - | - | - | | Latest npm release | 0.90.5, published 17 May 2025 | 4.1.39, published 6 November 2026 | | Last commit on `main` | 17 May 2025 | 5 October 2026 | | Open issues | 347, plus 24 open pull requests (GitHub shows 371 together) | 5, plus 10 open pull requests | | Downloads, 5 Sep to 4 Oct 2026 | 2,531,820 | 30,629 | | GitHub stars | 13,162 | 5,177 | Plasmo still installs and still builds. Downloads stay high because existing projects keep it pinned. There has been no release and no commit on `main` in over sixteen months. If your extension works today, you do not need to move. If you start a new extension, or need a bundler that still receives updates, read on. ## Migration paths If you are already on Plasmo and want to evaluate Extension.js, the typical migration touches four things: 1. Write a `manifest.json` by hand, mapping each convention file to a manifest entry and merging the `manifest` field from `package.json`. 2. Move content script `matches` from the exported `PlasmoCSConfig` into `content_scripts` in the manifest. 3. Rename `PLASMO_PUBLIC_*` to `EXTENSION_PUBLIC_*`. 4. Replace `plasmo dev`, `plasmo build`, and `plasmo package` with `extension dev` and `extension build --zip`. Your React components, Tailwind config, tests, and `chrome.*` calls copy over without changes. The full step-by-step guide, with the convention-to-manifest table and the CSUI replacement, is at [Migrate from Plasmo](/docs/migrate/from-plasmo). ## When to choose Extension.js * You want the manifest as the source of truth, not generated. * You want the CLI to launch the browser and load the extension for you. * You target Chrome, Edge, Firefox, and Safari from one tree and one command. * You want a bundler that still receives releases. * You want a docs MCP endpoint and `llms.txt` for your assistant. ## When to choose Plasmo * You prefer file-system convention over an explicit manifest. * You depend on CSUI anchors and the shadow-root mounting that it does for you. * You already publish through Browser Platform Publisher and your pinned toolchain still builds. ## See also * [Migrate from Plasmo](/docs/migrate/from-plasmo) * [Extension.js vs WXT](/docs/compare/extension-js-vs-wxt) * [Browser extension framework comparison](/docs/compare) * [Cross-browser compatibility](/docs/features/cross-browser-compatibility) * [Browser-specific manifest fields](/docs/features/browser-specific-fields) # Extension.js vs WXT Source: https://extension.js.org/docs/compare/extension-js-vs-wxt Side-by-side comparison of Extension.js and WXT for building cross-browser extensions. CLI ergonomics, manifest model, framework support, and reload behavior. Extension.js and [WXT](https://wxt.dev) are both modern frameworks for building cross-browser extensions. They overlap in mission and differ in philosophy. This page is a factual comparison so you can choose based on your project, not marketing copy. ## TL;DR: which should you pick? > [card] Choose Extension.js if… > > * You want the **`manifest.json` as the source of truth**, not generated from config. > * You like staying close to the native WebExtension model (real files, transparent output). > * You want to dev a remote sample with one command: `extension dev `. > * You want Rspack's Rust-speed builds and docs that your assistant can read: a docs MCP endpoint and `llms.txt` ([details](/docs/ai-access)). > [card] Choose WXT if… > > * You prefer **file-system convention** (`entrypoints/`) over an explicit manifest. > * You need **Manifest V2** as a primary target. > * You want `browser` auto-imported in every file, resolved to the native > `browser` object or to `chrome`. The rest of this page backs up that summary, dimension by dimension. ## At a glance | Dimension | Extension.js | WXT | | - | - | - | | Bundler | [Rspack](/docs/features/rspack-configuration) (Rust-based) | Vite (Rolldown migration in progress) | | Manifest | One `manifest.json`, browser-prefixed keys filtered at compile time | `wxt.config.ts` generates `manifest.json` per build | | Entrypoints | Files referenced from `manifest.json` | File-system convention under `entrypoints/` | | Browser targets | Chrome, Edge, Firefox, Safari (macOS, through Xcode), Chromium, Gecko, custom binaries | Chrome, Edge, Firefox, Safari (build only, no browser launch), custom binaries | | Manifest V3 | Default | Default | | Manifest V2 | Not supported as a primary target | Supported via `manifestVersion: 2` | | Reload model | HMR for popup/options/devtools, targeted reload for content scripts and SW | HMR for popup/options/devtools, targeted reload for content scripts | | `browser.*` polyfill | `--polyfill`, on by default in `dev` and off in `build` | `browser` aliased to `chrome`, real polyfill opt-in through `@wxt-dev/webextension-polyfill` | | Templates | React, Preact, Vue, Svelte, TypeScript, JavaScript, init | React, Vue, Svelte, Solid, vanilla | | TypeScript | First-class | First-class | | AI surfaces | Docs MCP endpoint + `llms.txt` ([details](/docs/ai-access)) | `llms.txt` available | ## Mental model **Extension.js stays close to the platform.** You author a `manifest.json` and reference real files. The CLI compiles, filters per browser, and ships. If you already understand how a browser extension is structured, the framework gets out of your way. **WXT abstracts the platform.** Entrypoints are inferred from a directory layout (`entrypoints/popup/`, `entrypoints/content.ts`), and the manifest is generated from your config and source. If you prefer convention over configuration, WXT does more for you per file you write. Neither approach is universally better. The choice depends on whether you want to **see** your manifest or **declare** your manifest. ## CLI surface ### Extension.js ```bash theme={null} npx extension@latest dev --browser=chrome,firefox npx extension@latest build --browser=chrome,firefox --zip npx extension@latest dev https://github.com/user/repo/tree/main/path ``` The argument can also be a remote GitHub URL or a ZIP archive, useful for spinning up a sample without cloning. See [Get started immediately](/docs/getting-started/immediately). ### WXT ```bash theme={null} wxt wxt build wxt build -b firefox wxt zip ``` WXT splits dev/build/zip into separate commands. Extension.js consolidates packaging into `build --zip`. ## Cross-browser strategy Both frameworks ship one codebase to multiple browsers, with different mechanics: * **Extension.js** uses [browser-prefixed manifest fields](/docs/features/browser-specific-fields) (`chrome:`, `firefox:`, `gecko:`, etc.) inside one `manifest.json`. The unprefixed keys apply everywhere, and prefixed keys land only in matching builds. * **WXT** computes the manifest from `wxt.config.ts` and per-target overrides. Browser differences live in TypeScript config rather than in the manifest itself. The two projects also reach the `browser` namespace differently. Extension.js bundles [webextension-polyfill](https://github.com/mozilla/webextension-polyfill) when you pass `--polyfill`, which `extension dev` does by default and `extension build` does not. WXT auto-imports a `browser` object from `wxt/browser`. As of wxt 0.21.4 that object is a native alias, `globalThis.browser` when the browser provides one and `globalThis.chrome` otherwise, so it is not a polyfill. The full polyfill is a separate opt-in module, `@wxt-dev/webextension-polyfill`. If your team includes designers or PMs who read `manifest.json`, prefixed keys keep that file as the source of truth. If your team wants extension config alongside other TypeScript config, WXT's approach reads more naturally. ## Migration paths If you are already on WXT and looking to evaluate Extension.js, the typical migration touches three things: 1. Move `entrypoints/` content back to flat files referenced from a hand-authored `manifest.json`. 2. Replace `wxt.config.ts` with [`extension.config.js`](/docs/features/extension-configuration) for build defaults. 3. Replace `wxt`/`wxt build` scripts with `extension dev`/`extension build`. Most React, Preact, Vue, and Svelte source files copy over without changes. The full step-by-step guide is at [Migrate from WXT](/docs/migrate/from-wxt). ## When to choose Extension.js * You want the manifest as the source of truth, not generated. * You want one CLI argument to dev a remote sample (`extension dev `). * You want a docs MCP endpoint and `llms.txt` for your assistant. * You want Rspack's Rust-speed compile times for large extensions. ## When to choose WXT * You prefer file-system convention over an explicit manifest. * You need Manifest V2 as a primary target. * You want `browser` auto-imported everywhere, with the full polyfill available as an opt-in module. ## See also * [Cross-browser compatibility](/docs/features/cross-browser-compatibility) * [Browser-specific manifest fields](/docs/features/browser-specific-fields) * [Templates](/docs/getting-started/templates) # Browser extension framework comparison Source: https://extension.js.org/docs/compare/index Compare browser extension frameworks: Extension.js, WXT, CRXJS, and Plasmo. Manifest model, bundler, cross-browser output, and migration guides for each. A browser extension framework handles the work that browsers do not. It compiles TypeScript and modern JavaScript for every extension surface, wires the manifest to real output files, reloads service workers and content scripts during development, and emits per-browser builds. This page compares the active options so you can choose with full information. Extension.js is a framework that builds and runs browser extensions from one `manifest.json` for Chrome, Edge, Firefox, and Safari. To create an extension, run these commands in a terminal: ```bash theme={null} npx extension@latest create my-extension cd my-extension npm install npm run dev ``` ## The frameworks | Dimension | Extension.js | WXT | CRXJS | Plasmo | | - | - | - | - | - | | Model | `manifest.json` as source of truth | File conventions + config | Vite plugin reading a manifest | File conventions | | Bundler | Rspack (internal, zero config) | Vite | Vite (plugin layer) | Parcel | | Cross-browser | Chrome, Edge, Firefox, Safari from one source | Chrome, Edge, Firefox, Safari (build only), MV2 | Chrome by default, Firefox through a `browser` option | Chrome MV3, Firefox MV2, Firefox MV3 (experimental) | | Setup | None required | `wxt.config.ts` | `vite.config.ts` + plugin | `package.json` manifest field | | Bundler coupling | Internal detail | Tracks Vite majors | Tracks Vite majors (3 to 8) | Tied to Parcel | Two structural differences matter more than any feature row: * **Where the manifest lives.** Extension.js reads your `manifest.json` and compiles whatever it declares. WXT and Plasmo generate the manifest from file conventions and config. CRXJS reads a manifest but resolves it through Vite's plugin API, so each Vite major needs CRXJS compatibility work. Vite 8 needed it (see [the Vite 8 fileName error](/docs/migrate/crxjs-content-script-filename-undefined)), and current CRXJS supports Vite 3 to 8. * **Who owns the bundler.** A framework that wraps a general-purpose bundler inherits that bundler's breaking changes. Extension.js treats the bundler as an internal detail: you never configure it, and upgrades are the framework's problem, not yours. ## Detailed comparisons and migrations * [Extension.js vs WXT](/docs/compare/extension-js-vs-wxt): the closest comparison, dimension by dimension. * [Extension.js vs Plasmo](/docs/compare/extension-js-vs-plasmo): manifest model, dev loop, packaging, and maintenance status with dates. * [Extension.js vs CRXJS](/docs/compare/extension-js-vs-crxjs): a framework that owns the bundler against a plugin inside your own Vite setup. * [Migrate from CRXJS](/docs/migrate/from-crxjs): step-by-step, about ten minutes for a typical project. * [Fix: Content script fileName is undefined](/docs/migrate/crxjs-content-script-filename-undefined): the CRXJS + Vite 8 build error, with workarounds. * [Migrate from Plasmo](/docs/migrate/from-plasmo): convention-to-manifest mapping, env vars, and CSUI. * [Migrate a webpack or Vite extension](/docs/migrate/from-webpack-or-vite): entries to manifest.json, loaders and plugins, and the traps that cost real migrations time. ## Try it without committing Run any extension template, or any extension repository on GitHub, with one command: ```bash theme={null} npx extension@latest dev ``` Your components, `chrome.*` calls, and styling carry over from any of these frameworks. The [migration guides](/docs/migrate/from-crxjs) cover the wiring that changes. # JavaScript and TypeScript extension files Source: https://extension.js.org/docs/concepts/javascript-typescript-browser-extension-files Learn how .js, .ts, .tsx, manifest.json, background scripts, and content scripts work in Chrome, Firefox, and Edge extensions built with Extension.js. Browser extensions use JavaScript, TypeScript, HTML, CSS, and a `manifest.json` to define behavior, UI, permissions, and browser integration. This page covers the file extensions you will see in a browser extension project and which ones land where. It is part of the Extension.js documentation: Extension.js builds and runs browser extensions from one `manifest.json` for Chrome, Edge, Firefox, and Safari, and compiles every file type below without configuration. Start a project with `npx extension@latest create my-extension`. If you are looking for "extension" as in a software add-on for Chrome or Firefox, start at [What is a browser extension?](/docs/concepts/what-is-a-browser-extension) instead. ## JavaScript file extensions: `.js` and `.mjs` Browser extensions accept the same JavaScript file extensions the rest of the web platform uses: | File extension | What it means | | - | - | | `.js` | Plain JavaScript. Treated as ES module or classic script depending on how it is loaded. | | `.mjs` | ES module. Useful when you want to force module semantics, especially in service workers. | | `.cjs` | CommonJS. Rare in extension source code; sometimes appears in `extension.config.cjs`. | In Manifest V3, the background `service_worker` runs as a module when `manifest.json` includes `"type": "module"` in the `background` block. See [Manifest V3 troubleshooting](/docs/concepts/manifest-v3) for the details. ## TypeScript file extensions: `.ts` and `.tsx` TypeScript works as a first-class source language in Extension.js: | File extension | What it means | | - | - | | `.ts` | TypeScript without JSX. | | `.tsx` | TypeScript with JSX (React, Preact). | | `.d.ts` | Type declaration file. Not emitted to the build output. | You do not need to write a `tsconfig.json` from scratch. Extension.js ships sensible defaults. Types for `chrome.*`, `browser.*`, `import.meta.env`, and the public env keys come from Extension.js's own ambient types. From Extension.js 4.1.19, the `@types/chrome` and `@types/webextension-polyfill` packages that those types need install with `extension`. See [Types for the chrome and browser APIs](/docs/languages-and-frameworks/extension-api-types) and [TypeScript](/docs/languages-and-frameworks/typescript). ## React file extensions: `.jsx` and `.tsx` React in a browser extension uses the standard JSX file extensions: | File extension | What it means | | - | - | | `.jsx` | JavaScript with JSX. | | `.tsx` | TypeScript with JSX. | React works inside extension pages (popup, options, side panel, new-tab) and inside content scripts injected into web pages. See [React](/docs/languages-and-frameworks/react) for setup and shadow-DOM patterns. ## Browser extension files: `manifest.json`, background, content scripts, pages Beyond JavaScript and TypeScript source, a browser extension folder usually contains: | File or folder | Purpose | | - | - | | `manifest.json` | Declares name, version, permissions, entry points, and metadata. | | Background entry | Long-lived event handler. Manifest V3 service worker on Chromium. | | Content scripts | Code injected into web pages matching a URL pattern. | | Extension pages | Popup, options, side panel, or new-tab HTML. | | Locales | `_locales//messages.json` for translated strings. | | Icons and assets | Toolbar icons, web-accessible resources, fonts, images. | Extension.js compiles your `.ts`, `.tsx`, `.jsx`, `.vue`, `.svelte`, `.css`, `.less`, `.scss`, and `.module.*` source down to that on-disk layout. It produces a separate folder per browser target (`dist/chrome`, `dist/firefox`, `dist/edge`). ## How Extension.js compiles JavaScript and TypeScript extensions When you run `extension dev` or `extension build`, Extension.js: 1. Reads `manifest.json` and finds every entry point (background, content scripts, popup, options, side panel, new-tab, web-accessible HTML). 2. Resolves source files referenced from those entries, including imports across `.ts`, `.tsx`, `.jsx`, `.vue`, `.svelte`, and stylesheet types. 3. Compiles through Rspack with extension-aware defaults: code splitting where it helps, no chunking where the browser refuses it (service workers, content scripts). 4. Emits the result into `dist/` with a manifest filtered for that target. You write source in any of the file extensions above. Extension.js handles the bundling, polyfills, reload-on-save loop, and per-browser packaging. ## Next steps * Try [`extension create`](/docs/commands/create) to scaffold a TypeScript or React extension. * Read [TypeScript](/docs/languages-and-frameworks/typescript) and [React](/docs/languages-and-frameworks/react). * Read [Manifest V3 troubleshooting](/docs/concepts/manifest-v3) for service worker and module rules. * Build with [`extension build`](/docs/commands/build). # Manifest V3 service workers and permissions Source: https://extension.js.org/docs/concepts/manifest-v3 How Manifest V3 changes service workers, content scripts, web_accessible_resources, and host_permissions, with the manifest.json fix for each common MV3 error. Manifest V3 (MV3) replaced background pages with service workers, tightened content security policy, and reshaped how extensions declare network and host access. Most day-to-day pain points share one root cause: MV3 assumes ephemeral, event-driven background code. Chrome and Firefox also interpret a few keys differently. Extension.js is a framework that builds and runs browser extensions from one `manifest.json` for Chrome, Edge, Firefox, and Safari. To create an extension, run these commands in a terminal: ```bash theme={null} npx extension@latest create my-extension cd my-extension npm install npm run dev ``` This page collects the issues that come up most often when building MV3 extensions, with the exact fix and what Extension.js handles for you. ## Manifest V3 background `service_worker` with `type: "module"` Chromium uses a service worker for the MV3 background. To import ES modules from it, the manifest needs `type: "module"`: ```json theme={null} { "manifest_version": 3, "background": { "service_worker": "service_worker.js", "type": "module" } } ``` Without `"type": "module"`, `import` statements fail at registration with no clear error in the extension console. With it, you can write modern ES module syntax in the worker file. Extension.js bundles your background entry, including `.ts`/`.tsx` workers, into a single output file, so `import` statements resolve at build time and the worker registers without `type: "module"`. Declare `type: "module"` yourself when you want a real module worker, and Extension.js keeps it in the emitted manifest. ## Why `background.js` behaves differently in Manifest V3 In Manifest V2, `background.js` ran in a persistent background page with a DOM. In Manifest V3 on Chromium, the background runs as a service worker: * No DOM. `window`, `document`, `XMLHttpRequest`, and `localStorage` are gone. Use `fetch` and `chrome.storage`. * The worker can be **terminated at any time** when idle and woken on the next event. Do not store state in module-scope variables; persist it in `chrome.storage`. * Top-level `await` is allowed, but long initialization will not keep the worker alive on its own. * Register event listeners **synchronously** at the top of the file, not inside async callbacks. Listeners registered inside async callbacks will not fire on the wake-up event that loaded the worker. Firefox keeps non-persistent event pages instead of service workers. Extension.js routes Chromium to `service_worker` and Firefox to `scripts` from the same source, so the same background entry compiles correctly per target. ## `web_accessible_resources` in Manifest V3 Manifest V3 changed `web_accessible_resources` from a flat array of files to a list of `{ resources, matches }` blocks: ```json theme={null} { "web_accessible_resources": [ { "resources": ["images/logo.png", "pages/injected.html"], "matches": ["https://example.com/*"] } ] } ``` Common mistakes: * Listing a path that is not in the build output. Extension.js only emits files that are referenced from `manifest.json`, the entry HTML, or imported code. Add the file as an asset so it lands in `dist/`. * Forgetting `matches`. Without it, the resource is not exposed to any origin. * Using V2-style flat strings. The browser silently ignores them in MV3. See [`web_accessible_resources` implementation](/docs/implementation-guide/web-accessible-resources) for the full pattern, including injecting an extension URL into a content script. ## `host_permissions` vs `permissions` Manifest V3 split host access out of the `permissions` array: | Key | What it controls | | - | - | | `permissions` | Named API surfaces (`storage`, `tabs`, `cookies`, `scripting`, `alarms`, etc.). | | `host_permissions` | URL match patterns the extension can read or modify (`https://*/*`, `*://api.example.com/*`). | | `optional_permissions` and `optional_host_permissions` | Permissions requested at runtime via `chrome.permissions.request`. | Symptoms of mixing them up: * `chrome.cookies.get` returning empty for a site you have access to: the URL needs `host_permissions`, not just `cookies`. * `chrome.scripting.executeScript` failing with "Cannot access contents of url": add the URL to `host_permissions`. * Web store warning users about "all-site" access when you only need one origin: narrow the host pattern. See [Permissions and host permissions](/docs/implementation-guide/permissions-and-host-permissions) for the per-API reference. ## `declarative_net_request` in Firefox `declarative_net_request` (DNR) is the MV3 replacement for blocking `webRequest`. Firefox supports it, but with a few constraints: * Static rule resource files (`rule_resources`) must be valid JSON arrays. Firefox is stricter about empty or malformed rule files than Chrome. * Some rule actions and conditions Chrome supports are still partial in Firefox. Check [MDN's `declarativeNetRequest` reference](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest) for the current matrix. * `host_permissions` (or ``) is required for DNR rules to apply on cross-origin requests. Extension.js validates the DNR resources at build time and emits per-browser artifacts so a Firefox-specific rule file does not end up in the Chrome build. ## Content scripts, workers, and extension URLs Three places where MV3 trips people up: * **Content scripts cannot access the page's JavaScript scope.** They share the DOM, not the window. Use `window.postMessage` (or a ` ``` ## Best practices * Keep module styles close to components (`Component.module.css`) for easier ownership. * Use `:global(...)` sparingly and only for intentional global overrides. * Prefer module styles for extension pages and framework components where class mapping is explicit. ## Next steps * Learn more about [Sass and Sass modules](/docs/languages-and-frameworks/sass). * Learn more about [Less and Less modules](/docs/languages-and-frameworks/less). ## Video walkthrough [Extension.js: Content CSS Modules template](https://www.youtube-nocookie.com/embed/ondh3B28ieQ?rel=0) # Deno projects with Extension.js Source: https://extension.js.org/docs/languages-and-frameworks/deno Scaffold and build browser extensions in Deno-first projects. Extension.js reads deno.jsonc as the project manifest and resolves npm: imports. Extension.js treats Deno as a first-class runtime, and a CI lane runs `extension build` and `extension dev` on Deno for every change. Scaffold with Deno and the project gets a `deno.jsonc` instead of a `package.json`. Work in a hybrid project and `deno.jsonc` sits beside `package.json` for Deno-native settings. Either way, `extension dev` and `extension build` behave the same. ## Which Deno versions work Extension.js needs Deno 2.5 or newer. The CLI reads `process.versions.deno` at startup and judges Deno on its own version, never on the Node version that Deno emulates, so the number in the message is the one you can act on. | Deno version | Status | | - | - | | 2.5 and newer | Supported, apart from 2.8.0 | | 2.8.0 | Refused. That release cannot resolve `node:querystring` inside the bundler, and Deno fixed it in 2.8.1 | | Older than 2.5 | Refused, because the floor is 2.5. As background, those releases also emulate a Node version below 22.12 | ## Create a project with Deno ```bash theme={null} deno run -A npm:extension@latest create my-extension --template=react ``` Then run the dev task: ```bash theme={null} cd my-extension deno task dev ``` ## Primary mode: deno.jsonc is the project manifest When you scaffold under the Deno runtime, `deno.jsonc` becomes the project's only manifest and `package.json` is removed. * Template dependencies move into `imports` as `npm:` specifiers, and `deno install` resolves them. * The `extension` engine itself is declared there too, as `npm:extension@`. * `nodeModulesDir` is set to `"auto"`, so `npm:` dependencies materialize in a real `node_modules` directory. The bundler resolves project dependencies from it at dev and build time. * `deno task ` also finds binaries in `node_modules/.bin`, so the generated tasks run the locally installed Extension.js CLI. A trimmed example: ```jsonc theme={null} { "imports": { "react": "npm:react@^19.0.0", "react-dom": "npm:react-dom@^19.0.0", "extension": "npm:extension@^4.0.0" }, "nodeModulesDir": "auto", "tasks": { "dev": "extension dev", "build": "extension build" } } ``` When a template ships its own Deno config, Extension.js merges into that file instead of creating a second one. Deno's own discovery prefers `deno.json` over `deno.jsonc`, so the merge targets the file that Deno will read. ## Companion mode: deno.jsonc beside package.json Monorepo templates, and projects that already have a `package.json`, keep it. Dependencies stay declared in `package.json`, and `deno install` resolves them from there. The companion `deno.jsonc` carries only Deno-native settings and the `tasks` that run the CLI. ## How the toolchain detects Deno Detection works on files, not on how you invoked the CLI: * Extension.js reads `deno.jsonc` or `deno.json` when it scans project dependencies. Framework, CSS, and TypeScript detection all see packages that `imports` declares through `npm:` specifiers. * When both manifests declare the same package, the `package.json` entry wins. * A project counts as Deno-managed when it has a `deno.lock`, or a Deno config with no `package.json` beside it. An npm-family lockfile wins for hybrids, and Deno is claimed only when the `deno` binary is on your PATH. ## TypeScript in Deno projects TypeScript detection follows the same rules as everywhere else. See [TypeScript](/docs/languages-and-frameworks/typescript): SWC compiles the sources, and the `typescript` package is only needed for `tsc --noEmit`. ## Managed browsers need Node.js `extension install ` downloads a managed browser through `npx`, or through the package manager that launched the CLI. `deno` has no such runner, so on Deno that one command needs Node.js on your `PATH`. Without it the command fails at the download step. `dev`, `build`, `preview`, and `start` run on Deno alone, and a browser that is already installed on your system needs no download. See [`install`](/docs/commands/install). ## Next steps * Learn how Extension.js handles [Node APIs](/docs/languages-and-frameworks/node). * Learn how to manage [Extension configuration](/docs/features/extension-configuration). # ECMAScript modules in extensions Source: https://extension.js.org/docs/languages-and-frameworks/ecmascript-modules Use modern import/export syntax across background scripts, content scripts, and extension pages. Extension.js supports ESM through its Rspack pipeline. Author extension code with modern `import`/`export` syntax across all extension contexts. Extension.js supports ECMAScript Modules (ESM) in background scripts, content scripts, and extension pages. It uses the default Rspack pipeline for module resolution. ## When ESM is a good fit * You want consistent module syntax across extension and web code. * You are sharing code with modern ESM-first packages. * You need cleaner tree-shaking (automatic removal of unused code) and explicit dependency boundaries. ## Template examples ### `new` ![new template screenshot](https://mintcdn.com/extensionjs/etcqPhDg4wwyPkcC/images/examples/newtab/screenshot.png?fit=max\&auto=format\&n=etcqPhDg4wwyPkcC\&q=85\&s=f4502f48e1600a3c3089c17fd89a9838) Start a new-tab extension with modern module syntax and minimal setup. ```bash npm theme={null} npx extension@latest create my-extension --template=newtab ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=newtab ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=newtab ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=newtab ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=newtab ``` Repository: [extension-js/templates/newtab](https://github.com/extension-js/templates/tree/main/examples/newtab) ### `content` ![content template screenshot](https://mintcdn.com/extensionjs/VCnDd7fX2Nza24SE/images/examples/content/screenshot.png?fit=max\&auto=format\&n=VCnDd7fX2Nza24SE\&q=85\&s=38b87862f852f3bed8473d947bd472ea) Inject script logic into page content while keeping ESM-style authoring. ```bash npm theme={null} npx extension@latest create my-extension --template=content ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=content ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=content ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=content ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=content ``` Repository: [extension-js/templates/content](https://github.com/extension-js/templates/tree/main/examples/content) ## Usage with an existing extension You can use ESM syntax directly in extension source files (`.js`, `.mjs`, `.ts`, `.tsx`, etc.) without custom bundler setup. If your Node.js project configuration files should also run as ESM, set `"type": "module"` in `package.json`. This applies to custom scripts and configuration conventions: ```json theme={null} { "name": "my-extension", "version": "1.0", "description": "My Extension Example", "type": "module", "devDependencies": { "extension": "latest" }, "scripts": { "dev": "extension dev", "start": "extension start", "build": "extension build" } } ``` ## Manifest and service worker notes For Manifest V3 background workers: * Set `background.type` to `"module"` when you want native ES module loading in the service worker. * Without module worker type, Extension.js uses classic worker loading (bundled scripts without native module syntax). ```json theme={null} { "background": { "service_worker": "src/background.ts", "type": "module" } } ``` ## ESM vs CommonJS reminders When writing ESM modules: ### Include file extensions in relative imports ```diff theme={null} // my-file.mjs import React from 'react' // local imports - import myImport from './myImport' + import myImport from './myImport.js' ``` ### Interoperability with non-ESM modules can differ When importing CommonJS packages from ESM, follow the compatibility guidance each package provides. ### CommonJS globals are not available in strict ESM contexts Avoid relying on `require`, `module.exports`, `__filename`, and `__dirname` inside ESM modules. ## Handling environment variables in ECMAScript modules Extension.js supports both: * `process.env.EXTENSION_PUBLIC_*` * `import.meta.env.EXTENSION_PUBLIC_*` Use `EXTENSION_PUBLIC_` for variables you want available in extension code. ```js theme={null} // example.mjs console.log(import.meta.env.EXTENSION_PUBLIC_API_URL); console.log(process.env.EXTENSION_PUBLIC_API_URL); ``` ## Do imports need mandatory file extensions? Node.js requires explicit file extensions in ESM import specifiers (`import "./util.js"`, never `import "./util"`). That rule applies to code Node runs directly, and it confuses people coming to extensions from server code. In Extension.js the bundler resolves imports, not Node, so both styles work in extension code: ```js theme={null} import { parse } from "./util"; // resolved by the bundler import { parse } from "./util.js"; // also fine ``` Two places the Node rule still matters: * Scripts your `package.json` runs with Node directly (build helpers, codegen): extensions are mandatory there. * `.mjs` files shared between Node tooling and extension code: write extensions so both resolvers accept them. ## Next steps * Learn more about [TypeScript](/docs/languages-and-frameworks/typescript). * Explore how Extension.js handles [CSS Modules](/docs/languages-and-frameworks/css-modules). # Types for the chrome and browser APIs Source: https://extension.js.org/docs/languages-and-frameworks/extension-api-types Get TypeScript types for chrome.*, browser.*, and process.env. Extension.js 4.1.19 and later installs them automatically; older versions need @types/chrome. Extension.js compiles TypeScript with SWC, which strips types and never checks them. Type checking is a separate step that you run with `tsc`. This page covers how that step resolves `chrome.*`, `browser.*`, and `process.env`. ## What Extension.js generates When a project uses TypeScript, `extension dev` and `extension build` write an `extension-env.d.ts` file beside `package.json`. It is regenerated on every run, so do not edit it. The file pulls in the ambient types that the `extension` package publishes: ```ts extension-env.d.ts theme={null} /// /// ``` Those references give you: | Reference | What it declares | | - | - | | `extension/types` | The `browser` global, the `chrome` namespace, `process.env` and `import.meta.env` keys | | `extension/types/polyfill` | The `browser.*` namespace shape from `webextension-polyfill` | | Wildcard modules | `import` of `.css`, `.module.css`, `.png`, `.svg`, and other assets, plus `?raw` and `?url` imports | The `EXTENSION_*` environment keys are typed here too. That is why `process.env.EXTENSION_MODE` resolves without extra setup. When the `extension` package does not resolve from the project, for example a project that only runs the CLI through `npx`, the two references find nothing. The generated file then also carries the wildcard module declarations inline, so stylesheet, image, `?raw`, and `?url` imports still type-check. ## Types that install with Extension.js From Extension.js 4.1.19, the `extension` package lists the three type packages that its references need as dependencies: | Package | What it types | | - | - | | `@types/chrome` | The `chrome.*` namespace | | `@types/webextension-polyfill` | The `browser.*` namespace | | `@types/node` | `process.env` | They install with `extension`, so `tsc` resolves `chrome.*` and `browser.*` in a new project without an extra install: ```bash theme={null} npx tsc --noEmit ``` The build does not need these packages. SWC never reads the types, so the build succeeds with or without them. ## Pin your own version The `extension` package accepts any version of the three type packages. When your project declares one of them, npm, pnpm, and Bun reuse the copy that your project installs. When your `tsconfig.json` has no `types` array, TypeScript also loads the copy that your project declares. The version in your own `package.json` wins: ```json package.json theme={null} { "devDependencies": { "@types/chrome": "^0.0.287" } } ``` ## Projects on Extension.js 4.1.18 or older Before 4.1.19, `extension/types` referenced `chrome` but did not install `@types/chrome`. A project that calls `chrome.*` without its own copy fails `tsc`: ```plaintext theme={null} src/background.ts(19,1): error TS2304: Cannot find name 'chrome'. src/content/scripts.ts(87,30): error TS2503: Cannot find namespace 'chrome'. ``` Upgrade `extension` to 4.1.19 or later. If you stay on an older version, install the package by hand: ```bash npm theme={null} npm install -D @types/chrome ``` ```bash pnpm theme={null} pnpm add -D @types/chrome ``` ```bash yarn theme={null} yarn add -D @types/chrome ``` ```bash bun theme={null} bun add -d @types/chrome ``` ```bash deno theme={null} deno add -D npm:@types/chrome ``` On those versions, `browser` has the type `any` until `@types/webextension-polyfill` is installed. To type `browser.*`, install that package too: ```bash npm theme={null} npm install -D @types/webextension-polyfill ``` ```bash pnpm theme={null} pnpm add -D @types/webextension-polyfill ``` ```bash yarn theme={null} yarn add -D @types/webextension-polyfill ``` ```bash bun theme={null} bun add -d @types/webextension-polyfill ``` ```bash deno theme={null} deno add -D npm:@types/webextension-polyfill ``` ## Type errors on browser.\* after an upgrade From 4.1.19, `browser` has the full `webextension-polyfill` type instead of `any`. Code that passed `tsc` before can show new type errors, for example a call to an API that the polyfill does not declare. Fix the call, or use `chrome.*` for an API that only Chromium ships. Read [Cross-browser compatibility](/docs/features/cross-browser-compatibility) for the runtime side of the same choice. ## Keep extension-env.d.ts in the include list The generated file only helps when TypeScript reads it. The scaffolded `tsconfig.json` names it: ```json tsconfig.json theme={null} { "include": ["./", "extension-env.d.ts"], "exclude": ["node_modules", "dist"] } ``` When Extension.js writes a `tsconfig.json` for a project that has none, that file carries no `include` array. TypeScript then reads every file under the project folder, so it finds `extension-env.d.ts` anyway. An `include` array of your own that omits the file breaks asset imports and the `browser` global. From the release after 4.1.39, Extension.js creates the file only when your `tsconfig.json` would read it beside `package.json`. That is the case with no `include` array, with an `include` that covers the project root, or when `include` or `files` names the file. With a narrower `include` such as `["src"]`, the file is not created, so add it: ```json tsconfig.json theme={null} { "include": ["src", "extension-env.d.ts"] } ``` A copy that already exists is kept up to date either way. Reformatting it, for example with other quotes or without semicolons, does not trigger a rewrite. ## Symptoms and fixes | Symptom | Cause | Fix | | - | - | - | | `Cannot find name 'chrome'` | Extension.js 4.1.18 or older, and no `@types/chrome` | Upgrade to 4.1.19, or install `@types/chrome` | | `Cannot find namespace 'chrome'` | Same cause, in a type position | Upgrade to 4.1.19, or install `@types/chrome` | | `Cannot find module './styles.css'` | `extension-env.d.ts` is out of `include` | Add the file to `include` | | `Cannot find name 'browser'` | The project never ran `dev` or `build` | Run either command once to generate types | | New type errors on `browser.*` calls | From 4.1.19, `browser` is typed instead of `any` | Fix the call, or use `chrome.*` for a Chromium-only API | ## Best practices * Treat `extension-env.d.ts` as build output. Commit it if you like, but never edit it. * Declare a type package in your own `devDependencies` only when you need a specific version of it. * Run `tsc --noEmit` in continuous integration. The Extension.js build does not fail on type errors. ## Next steps * Read the rest of the [TypeScript setup](/docs/languages-and-frameworks/typescript). * Learn about [environment variables](/docs/features/environment-variables) that the types declare. * Review [cross-browser compatibility](/docs/features/cross-browser-compatibility). # Languages and frameworks guide Source: https://extension.js.org/docs/languages-and-frameworks/index See which languages and frameworks Extension.js supports including TypeScript, React, Vue, Svelte, Preact, Sass, Less, CSS Modules, and WebAssembly. Choose the right language and UI framework strategy for your extension surfaces, then use Extension.js defaults to keep setup minimal. ## Choose by goal | Goal | Start here | | - | - | | Strong typing and safer refactors | [TypeScript](/docs/languages-and-frameworks/typescript) | | Rich UI components with large ecosystem | [React](/docs/languages-and-frameworks/react) | | Smaller React-like runtime | [Preact](/docs/languages-and-frameworks/preact) | | Vue single-file component workflow | [Vue.js](/docs/languages-and-frameworks/vue) | | Compiled components with minimal runtime | [Svelte](/docs/languages-and-frameworks/svelte) | | Modern module syntax | [ECMAScript modules](/docs/languages-and-frameworks/ecmascript-modules) | | Scoped styling by default | [CSS Modules](/docs/languages-and-frameworks/css-modules) | | Sass or Less styling workflows | [Sass](/docs/languages-and-frameworks/sass), [Less](/docs/languages-and-frameworks/less) | | Browser-safe Node compatibility decisions | [Node APIs in browser extensions](/docs/languages-and-frameworks/node) | | Performance-heavy wasm workloads | [WebAssembly](/docs/languages-and-frameworks/webassembly) | Extension.js detects and configures four UI frameworks: React, Preact, Vue, and Svelte. Solid is not supported today. ## Suggested progression 1. Choose language/runtime (`TypeScript`, `React`, `Preact`, `Vue`, or `Svelte`). 2. Choose styling model (`CSS Modules`, `Sass`, or `Less`). 3. Add build/runtime constraints (`Node APIs`, `WebAssembly`) only when needed. JSX pages compile for the framework the project installs: React, Preact, and Vue (through `vue/jsx-runtime`). Svelte components are not JSX and keep compiling through `svelte-loader`. The parser follows the file extension: `.tsx` and `.jsx` files parse JSX, and a `.ts` file never does. ## Next steps * Add ecosystem tooling in [Integrations](/docs/integrations/index). * Keep command usage clear in [Commands reference](/docs/commands/index). # Less CSS in browser extensions Source: https://extension.js.org/docs/languages-and-frameworks/less Use Less CSS and Less modules across browser extension pages and UI components. Extension.js configures the Rspack preprocessor for .less files. Use Less CSS across browser extension pages and UI components with a single pipeline that also supports module-scoped styles. Extension.js detects Less usage, configures the preprocessors in the Rspack build, and supports both `.less` and `.module.less` files in browser extensions. ## When Less is a good fit * You are migrating an existing Less-based web codebase. * You want variables and nesting with low migration cost. * You need module-scoped styles while keeping Less conventions. ## Template examples ### `new-less` ![new-less template screenshot](https://mintcdn.com/extensionjs/etcqPhDg4wwyPkcC/images/examples/newtab-less/screenshot.png?fit=max\&auto=format\&n=etcqPhDg4wwyPkcC\&q=85\&s=4dbd571767c198bb8191fbb7ac918a3b) Start a new-tab extension with Less support already configured. ```bash npm theme={null} npx extension@latest create my-extension --template=newtab-less ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=newtab-less ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=newtab-less ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=newtab-less ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=newtab-less ``` Repository: [extension-js/templates/newtab-less](https://github.com/extension-js/templates/tree/main/examples/newtab-less) ## Usage with an existing extension Add Less to an existing extension with the steps below. ### Installation Install the required dependencies: ```bash npm theme={null} npm install -D less less-loader ``` ```bash pnpm theme={null} pnpm add -D less less-loader ``` ```bash yarn theme={null} yarn add -D less less-loader ``` ```bash bun theme={null} bun add -d less less-loader ``` ```bash deno theme={null} deno add -D npm:less npm:less-loader ``` ### Example usage in an HTML file In extension pages (popup/options/new tab), import Less through your script entry: ```html theme={null} New Extension

Hello, Extension.

``` ```ts theme={null} import "./styles/globals.less"; console.log("Less loaded"); ``` ### In a `content_script` file Load the compiled sheet into your shadow root, as the `content-less` template does: ```ts theme={null} export default function initial() { const rootDiv = document.createElement("div"); rootDiv.setAttribute("data-extension-root", "true"); rootDiv.style.cssText = "all: initial !important"; document.body.appendChild(rootDiv); const shadowRoot = rootDiv.attachShadow({ mode: "open" }); const styleElement = document.createElement("style"); shadowRoot.appendChild(styleElement); fetchCSS().then((css) => (styleElement.textContent = css)); const contentDiv = document.createElement("div"); contentDiv.className = "content_script"; shadowRoot.appendChild(contentDiv); return () => rootDiv.remove(); } async function fetchCSS() { const cssUrl = new URL("./styles/content.less", import.meta.url); const response = await fetch(cssUrl); const text = await response.text(); return response.ok ? text : Promise.reject(text); } ``` A plain `import "./styles/content.less"` styles nothing in a content script. See [CSS, Sass, and Less](/docs/implementation-guide/css) for every route. ## Less modules in browser extensions Scope class names locally with Less modules, just like CSS Modules. This prevents global style conflicts by default, which matters in extensions because content scripts run inside a host page's CSS scope. ### `content-less-modules` ![content-less-modules template screenshot](https://mintcdn.com/extensionjs/VCnDd7fX2Nza24SE/images/examples/content-less-modules/screenshot.png?fit=max\&auto=format\&n=VCnDd7fX2Nza24SE\&q=85\&s=b83981ec241b8de1fd6ac771510234b3) Use Less modules in content scripts when you need scoped styles on injected UI. ```bash npm theme={null} npx extension@latest create my-extension --template=content-less-modules ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=content-less-modules ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=content-less-modules ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=content-less-modules ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=content-less-modules ``` Repository: [extension-js/templates/content-less-modules](https://github.com/extension-js/templates/tree/main/examples/content-less-modules) ## Using Less modules in an existing extension To enable Less modules, rename your `.less` files to include `.module.less`. This enables automatic local scoping of class names. ```diff theme={null} - myStyles.less + myStyles.module.less ``` ### Example usage After renaming your Less file, you can import it into your scripts: ```ts theme={null} import styles from "./styles/myStyles.module.less"; const element = document.createElement("h1"); element.className = styles.primary; element.innerText = "Hello, Extension!"; document.body.appendChild(element); ``` ## React/Preact example usage To use Less modules in React or Preact, import your Less module and apply styles as you would in any component: ```jsx theme={null} import styles from "./styles/myStyles.module.less"; export default function MyComponent() { return

Hello, Extension!

; } ``` ## Vue example usage In Vue, prefer single-file component (SFC) styles with `lang="less"` and `module`: ```vue theme={null} ``` ## Svelte example usage In Svelte, import Less module mappings and apply classes: ```svelte theme={null}

Hello, Extension!

``` ## Behavior notes * In extension page contexts, `.module.less` exports class maps as expected. * In content scripts, Extension.js emits styles as CSS assets and injects them as stylesheets into the page. * If the `less` package is not installed, Extension.js warns and copies the raw Less source into the output CSS, so those surfaces render unstyled until you install it yourself. ## About the `less` post-install warning With some package managers, installing a project that uses Less can surface a notice that build scripts for `less` were not run (pnpm prints `Ignored build scripts: less` and asks you to approve them). This is expected and **safe to ignore**. Extension.js compiles Less through its own bundler pipeline, so it does not rely on Less's optional post-install step (which only sets up Playwright inside Less's own repository and is a no-op for consumers). Your `.less` and `.module.less` files build and hot-reload the same either way. Scaffolded projects do not ship a `pnpm.ignoredBuiltDependencies` key, so a pnpm install of a Less template shows the notice like any other project. npm and yarn run the script by default and print nothing. If you hit the notice, you have two equivalent ways to silence it: * **Skip it (recommended)**: add `pnpm.ignoredBuiltDependencies: ["less"]` to your `package.json`. This acknowledges the script without running the no-op. * **Run it**: run `pnpm approve-builds` and select `less`, or add `pnpm.onlyBuiltDependencies: ["less"]`. Harmless, just unnecessary. Either way there is no functional difference for typical Extension.js projects. ## Next steps * Learn more about [CSS Modules](/docs/languages-and-frameworks/css-modules). * Configure [PostCSS](/docs/integrations/postcss) in your extension. ## Video walkthrough [Extension.js: Content Less template](https://www.youtube-nocookie.com/embed/VGssDbxBeMM?rel=0) # Node APIs in browser extensions Source: https://extension.js.org/docs/languages-and-frameworks/node Use browser-native APIs first, then selectively polyfill Node core modules when needed. Extension.js targets the browser runtime by default. Extension.js targets the browser runtime by default. It does not automatically polyfill Node core modules, which keeps bundles small. If a dependency reaches for `buffer`, `stream`, or `os`, you see a resolution error at build time. The sections below explain when to add polyfills and when to choose a browser-native alternative. ## When Node polyfills are a good fit * A required dependency needs Node core modules in browser runtime. * You are incrementally migrating code from Node-centric packages. * You can accept larger bundles for specific runtime capabilities. ## Template examples ### `new-typescript` ![new-typescript template screenshot](https://mintcdn.com/extensionjs/etcqPhDg4wwyPkcC/images/examples/newtab-typescript/screenshot.png?fit=max\&auto=format\&n=etcqPhDg4wwyPkcC\&q=85\&s=b231ca6fb2357d932e40b7e2febc1aa5) Start from a TypeScript baseline when your extension needs explicit bundler/polyfill tuning. ```bash npm theme={null} npx extension@latest create my-extension --template=newtab-typescript ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=newtab-typescript ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=newtab-typescript ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=newtab-typescript ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=newtab-typescript ``` Repository: [extension-js/templates/newtab-typescript](https://github.com/extension-js/templates/tree/main/examples/newtab-typescript) ### `content-typescript` ![content-typescript template screenshot](https://mintcdn.com/extensionjs/VCnDd7fX2Nza24SE/images/examples/content-typescript/screenshot.png?fit=max\&auto=format\&n=VCnDd7fX2Nza24SE\&q=85\&s=38daa68927a34f112b6ecb63a9f6ab17) Use a content-script TypeScript base when Node-dependent libraries run inside page-injected flows. ```bash npm theme={null} npx extension@latest create my-extension --template=content-typescript ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=content-typescript ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=content-typescript ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=content-typescript ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=content-typescript ``` Repository: [extension-js/templates/content-typescript](https://github.com/extension-js/templates/tree/main/examples/content-typescript) ### `new-crypto` ![new-crypto template screenshot](https://mintcdn.com/extensionjs/etcqPhDg4wwyPkcC/images/examples/newtab-crypto/screenshot.png?fit=max\&auto=format\&n=etcqPhDg4wwyPkcC\&q=85\&s=51997b2fa10e44c60ad7f848634fc233) See the Web Crypto API (`window.crypto.subtle`) used directly in a new-tab extension, no polyfill. ```bash npm theme={null} npx extension@latest create my-extension --template=newtab-crypto ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=newtab-crypto ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=newtab-crypto ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=newtab-crypto ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=newtab-crypto ``` Repository: [extension-js/templates/newtab-crypto](https://github.com/extension-js/templates/tree/main/examples/newtab-crypto) ## Default behavior * Build target is browser-first (`web`). * Resolution prioritizes browser exports (`browser`, `module`, `main`). * `crypto`, `path`, and `fs` are mapped to `false`, so they resolve to an empty module. The build succeeds and the import fails at runtime instead (for example `path.join` is undefined). * Every other Node core module, including `buffer`, `stream`, `os` and `node:`-prefixed specifiers, has no fallback and fails the build with `Module not found: Can't resolve`. So a missing Node API shows up in one of two places, and which one depends on the module. Add explicit fallbacks below to handle either case. ### `node:` specifiers and the build error From the release after 4.1.39, `node:fs` and `fs` are the same request, so both spellings get the same answer: * `crypto`, `fs`, and `path` resolve to an empty module under either spelling. That includes a subpath such as `fs/promises`. * Any other built-in stops the build. The message names the built-in, the file that imports it, and the `resolve.fallback` key to set. * A `require()` of a built-in with no stand-in is a warning. The call stays verbatim in the output and throws only if that code path runs. Set `EXTENSION_STRICT_REFS=true` to fail the build on it. ```plaintext theme={null} The Node.js built-in util does not exist in a browser, and this build has no stand-in for it. background.js imports it. Only crypto, fs, path are replaced with an empty module. In extension.config.js, set resolve.fallback from the config hook: {'util': false} for an empty module, or the path of a browser polyfill you installed, such as require.resolve('util/'). node:util and util read the same key. ``` On 4.1.39 and earlier, a `node:`-prefixed specifier fails the build for every module, `crypto`, `fs`, and `path` included. ## Setting up Node polyfills Use `extension.config.js` (or `.mjs` / `.cjs`) to extend the Rspack configuration and define safe fallbacks. ```js theme={null} import NodePolyfillPlugin from "node-polyfill-webpack-plugin"; import { createRequire } from "node:module"; const require = createRequire(import.meta.url); export default { config: (config) => { config.resolve = config.resolve || {}; config.resolve.fallback = { ...(config.resolve.fallback || {}), crypto: require.resolve("crypto-browserify"), path: require.resolve("path-browserify"), fs: false, }; config.plugins = config.plugins || []; config.plugins.push(new NodePolyfillPlugin()); return config; }, }; ``` ### Add one fallback at a time You do not need a polyfill plugin for one or two modules. Install the browser packages, then extend `resolve.fallback` from the `config` hook. Set a key to `false` for an empty module. `Buffer` is a global in Node.js, so provide it with a `ProvidePlugin`. From the release after 4.1.39, the hook's second argument carries `rspack`, the bundler that Extension.js compiles with. Take the plugin class from it, so your project needs no `@rspack/core` of its own: ```bash npm theme={null} npm install buffer util ``` ```bash pnpm theme={null} pnpm add buffer util ``` ```bash yarn theme={null} yarn add buffer util ``` ```bash bun theme={null} bun add buffer util ``` ```bash deno theme={null} deno add npm:buffer npm:util ``` ```js extension.config.js theme={null} import { createRequire } from "node:module"; const require = createRequire(import.meta.url); export default { config: (config, { rspack }) => { config.resolve.fallback = { ...config.resolve.fallback, buffer: require.resolve("buffer/"), util: require.resolve("util/"), os: false, }; config.plugins.push( new rspack.ProvidePlugin({ Buffer: ["buffer", "Buffer"] }), ); return config; }, }; ``` Spread the existing `resolve.fallback` so the three default keys stay. The trailing slash in `require.resolve("buffer/")` names the installed package, not the Node.js built-in. A name that exists only with the prefix, such as `node:test`, has no bare key for `resolve.fallback` to reach. Replace it with a module of your own through `rspack.NormalModuleReplacementPlugin`: ```js extension.config.js theme={null} import { createRequire } from "node:module"; const require = createRequire(import.meta.url); export default { config: (config, { rspack }) => { config.plugins.push( new rspack.NormalModuleReplacementPlugin( /^node:test$/, require.resolve("./src/test-stand-in.js"), ), ); return config; }, }; ``` ## Install optional polyfill packages ```bash npm theme={null} npm install -D node-polyfill-webpack-plugin crypto-browserify path-browserify ``` ```bash pnpm theme={null} pnpm add -D node-polyfill-webpack-plugin crypto-browserify path-browserify ``` ```bash yarn theme={null} yarn add -D node-polyfill-webpack-plugin crypto-browserify path-browserify ``` ```bash bun theme={null} bun add -d node-polyfill-webpack-plugin crypto-browserify path-browserify ``` ```bash deno theme={null} deno add -D npm:node-polyfill-webpack-plugin npm:crypto-browserify npm:path-browserify ``` ## Extension APIs vs Node APIs Setting `polyfill: true` in CLI/config enables `webextension-polyfill`, a compatibility layer that gives Chromium browsers older than 148 access to the `browser.*` API namespace (older than 152 with a `devtools_page`). Newer versions expose `browser` natively. It does not enable Node core module polyfills. Use Node polyfills only for libraries that cannot run with standard Web APIs. ## Caveats * Do not assume filesystem access in extension runtime; keep `fs: false` unless you have a specific browser-safe strategy. * Prefer Web Crypto (`crypto.subtle`) over large Node crypto shims when possible. * Polyfills (browser-compatible replacements for Node APIs) increase bundle size and can affect startup time in extension pages and content scripts. * From the release after 4.1.39, a `node:` specifier reads the same `resolve.fallback` key as its bare name. On earlier versions, it fails the build. ## Next steps * Learn how to customize [Rspack configuration](/docs/features/rspack-configuration). * Learn how to manage [Extension configuration](/docs/features/extension-configuration). ## Video walkthrough [Extension.js: New Tab Crypto template](https://www.youtube-nocookie.com/embed/dPdh5H_sTgw?rel=0) # Preact for browser extensions Source: https://extension.js.org/docs/languages-and-frameworks/preact Ship smaller extension UI bundles with Preact while keeping a React-like DX. Extension.js auto-configures JSX transforms and compat aliases. Ship smaller extension UI bundles while keeping a React-like developer experience and fast local iteration. Extension.js detects Preact from your dependencies. It configures JSX/TSX transforms and React compatibility aliases automatically. Your React imports map to Preact through these aliases. In development, edits apply through live reload: the changed surface reloads rather than hot-swapping components in place. ## When Preact is a good fit * You want smaller UI bundle size for popup/sidebar/new tab surfaces. * You like React-style components but want a lighter runtime. * You are optimizing extension startup and UI responsiveness on lower-end devices. ## Template examples ### `new-preact` ![Template screenshot](https://mintcdn.com/extensionjs/etcqPhDg4wwyPkcC/images/examples/newtab-preact/screenshot.png?fit=max\&auto=format\&n=etcqPhDg4wwyPkcC\&q=85\&s=025286a96259496ef57329d3217d9baf) Ship a lighter new-tab UI with Preact and React-compatible ergonomics. ```bash npm theme={null} npx extension@latest create my-extension --template=newtab-preact ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=newtab-preact ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=newtab-preact ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=newtab-preact ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=newtab-preact ``` Repository: [extension-js/templates/newtab-preact](https://github.com/extension-js/templates/tree/main/examples/newtab-preact) ### `content-preact` ![Template screenshot](https://mintcdn.com/extensionjs/VCnDd7fX2Nza24SE/images/examples/content-preact/screenshot.png?fit=max\&auto=format\&n=VCnDd7fX2Nza24SE\&q=85\&s=0e7851109ce667ffb90e28801877adcf) Inject a compact Preact UI into page content using content scripts. ```bash npm theme={null} npx extension@latest create my-extension --template=content-preact ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=content-preact ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=content-preact ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=content-preact ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=content-preact ``` Repository: [extension-js/templates/content-preact](https://github.com/extension-js/templates/tree/main/examples/content-preact) ## Usage with an existing extension Add Preact to an existing extension with the steps below. ### Installation Install the required dependencies: ```bash npm theme={null} npm install preact ``` ```bash pnpm theme={null} pnpm add preact ``` ```bash yarn theme={null} yarn add preact ``` ```bash bun theme={null} bun add preact ``` ```bash deno theme={null} deno add npm:preact ``` Preact ships its own TypeScript types, so you do not need a separate `@types/preact` package. `preact` is the only package you add. Extension.js resolves `preact/compat`, `preact/test-utils`, and the JSX runtimes from your project and builds the alias map from whatever it finds, so there is no extra package to install. Preact 10 and Preact 11 both work. Builds, rendering, and hooks behave the same on either version. If you use `@preact/signals` with Preact 11, install `@preact/signals` 2.0.4 or later, because 1.x and 2.0.0 to 2.0.3 accept only Preact 10 as a peer. ### Configuration Extension.js expects Preact files to use the following file extensions: * If you do not enable TypeScript: `*.jsx` * If you enable TypeScript: `*.tsx` ## Development behavior When Extension.js detects Preact, it configures: * Compatibility aliases (for example, `react` → `preact/compat`). * JSX handling tuned for Preact. * Live reload in development: when a file changes, the affected surface reloads and remounts. Unlike React, Preact does not currently get fast refresh (state-preserving hot updates). The upstream `@rspack/plugin-preact-refresh` runtime is incompatible with the Rspack version Extension.js ships, so Extension.js disables it rather than break dev mode. Your app still updates on every edit, and component state is just not preserved across edits. Fast refresh returns once the upstream plugin is fixed. ### Troubleshooting * **Component state resets on edit:** Expected for now, because Preact uses live reload, not fast refresh (see above). * **No Preact integration detected:** Confirm `preact` appears in `dependencies` or `devDependencies`. ## Usage examples ### In a new tab extension To use Preact in a new tab extension, include it as a ` ``` ```tsx theme={null} import { h, render } from "preact"; import App from "./App"; const root = document.getElementById("root"); render(, root); ``` ```tsx theme={null} export default function App() { return

Hello, Preact Extension!

; } ``` ### In a `content_script` file For content scripts, render Preact inside a shadow root, and load the stylesheet into that root: ```tsx theme={null} import { render } from "preact"; import App from "./App"; export default function initial() { const rootDiv = document.createElement("div"); rootDiv.setAttribute("data-extension-root", "true"); rootDiv.style.cssText = "all: initial !important"; document.body.appendChild(rootDiv); const shadowRoot = rootDiv.attachShadow({ mode: "open" }); const styleElement = document.createElement("style"); shadowRoot.appendChild(styleElement); fetchCSS().then((css) => (styleElement.textContent = css)); const container = document.createElement("div"); shadowRoot.appendChild(container); render(, container); return () => { render(null, container); rootDiv.remove(); }; } async function fetchCSS() { const cssUrl = new URL("./content.css", import.meta.url); const response = await fetch(cssUrl); const text = await response.text(); return response.ok ? text : Promise.reject(text); } ``` A plain `import "./content.css"` styles nothing in a content script. See [CSS, Sass, and Less](/docs/implementation-guide/css) for every route. ## Next steps * Learn more about [TypeScript support](/docs/languages-and-frameworks/typescript). * Explore how Extension.js handles [Sass modules](/docs/languages-and-frameworks/sass). ## Video walkthrough [Extension.js: Preact HMR](https://www.youtube-nocookie.com/embed/8xNBQ3ryBWk?rel=0) ## See the template run [Extension.js: Content Preact template](https://www.youtube-nocookie.com/embed/sYA3V9YIWwo?rel=0) # React for browser extensions Source: https://extension.js.org/docs/languages-and-frameworks/react Build browser extension UIs with React using Extension.js. Get auto-configured JSX transforms, aliases, and fast refresh during development. Extension.js detects React from your project dependencies and configures JSX/TSX transforms, React module aliases, and fast-refresh support for development automatically. ## When React is a good fit * You are building rich UI surfaces like popup, options, sidebar, or new tab. * You want component reuse across extension pages and content-script UI mounts. * You already use React in web projects and want the same development model in extensions. ## Template examples ### `new-react` ![new-react template screenshot](https://mintcdn.com/extensionjs/etcqPhDg4wwyPkcC/images/examples/newtab-react/screenshot.png?fit=max\&auto=format\&n=etcqPhDg4wwyPkcC\&q=85\&s=9403c8f39160cb9b7d524271ba5d4525) Build a React new-tab experience with a ready-to-run project structure. ```bash npm theme={null} npx extension@latest create my-extension --template=newtab-react ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=newtab-react ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=newtab-react ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=newtab-react ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=newtab-react ``` Repository: [extension-js/templates/newtab-react](https://github.com/extension-js/templates/tree/main/examples/newtab-react) ### `content-react` ![content-react template screenshot](https://mintcdn.com/extensionjs/VCnDd7fX2Nza24SE/images/examples/content-react/screenshot.png?fit=max\&auto=format\&n=VCnDd7fX2Nza24SE\&q=85\&s=a0b8694d3a7dfdbb38944a1a7c183c58) Inject React UI into existing pages with a content-script-first setup. ```bash npm theme={null} npx extension@latest create my-extension --template=content-react ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=content-react ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=content-react ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=content-react ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=content-react ``` Repository: [extension-js/templates/content-react](https://github.com/extension-js/templates/tree/main/examples/content-react) ### `new-react-router` ![new-react-router template screenshot](https://mintcdn.com/extensionjs/etcqPhDg4wwyPkcC/images/examples/newtab-react-router/screenshot.png?fit=max\&auto=format\&n=etcqPhDg4wwyPkcC\&q=85\&s=3782fe989c78570a923ffb95951d15f3) React extension with client-side routing using React Router. ```bash npm theme={null} npx extension@latest create my-extension --template=newtab-react-router ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=newtab-react-router ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=newtab-react-router ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=newtab-react-router ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=newtab-react-router ``` Repository: [extension-js/templates/newtab-react-router](https://github.com/extension-js/templates/tree/main/examples/newtab-react-router) ## Usage with an existing extension Add React to an existing extension with the steps below. ### Installation Install React runtime dependencies: ```bash npm theme={null} npm install react react-dom ``` ```bash pnpm theme={null} pnpm add react react-dom ``` ```bash yarn theme={null} yarn add react react-dom ``` ```bash bun theme={null} bun add react react-dom ``` ```bash deno theme={null} deno add npm:react npm:react-dom ``` If you use TypeScript, also install React type packages: ```bash npm theme={null} npm install -D @types/react @types/react-dom ``` ```bash pnpm theme={null} pnpm add -D @types/react @types/react-dom ``` ```bash yarn theme={null} yarn add -D @types/react @types/react-dom ``` ```bash bun theme={null} bun add -d @types/react @types/react-dom ``` ```bash deno theme={null} deno add -D npm:@types/react npm:@types/react-dom ``` The React integration also uses optional packages such as `react-refresh` and `@rspack/plugin-react-refresh`. Both ship as dependencies of `extension-develop`, so a healthy install already resolves them. When one cannot be resolved, the build fails to start and the error names the packages to install. The install command in the error is phrased for the package manager that your project uses. ### Configuration Common React file patterns: * JavaScript: `*.jsx` * TypeScript: `*.tsx` ## Development behavior In development mode, Extension.js enables React refresh integration when it detects React. * Extension.js uses `react-refresh` and `@rspack/plugin-react-refresh` for refresh behavior. * If the refresh packages cannot be resolved from your project or from `extension-develop`, the build fails to start and prints that install command. Extension.js does not install them for you and does not ask for a restart. * Extension.js applies React aliases to keep a single React/runtime instance in your bundle. ## Usage examples ### In a new tab extension Example page entry: ```html theme={null} New Extension
``` ```tsx theme={null} import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( , ); ``` ```tsx theme={null} export default function App() { return

Hello, Extension!

; } ``` ### In a `content_script` file For content scripts, render React inside a shadow root, and load the stylesheet into that root: ```tsx theme={null} import ReactDOM from "react-dom/client"; import App from "./App"; export default function initial() { const rootDiv = document.createElement("div"); rootDiv.setAttribute("data-extension-root", "true"); rootDiv.style.cssText = "all: initial !important"; document.body.appendChild(rootDiv); const shadowRoot = rootDiv.attachShadow({ mode: "open" }); const styleElement = document.createElement("style"); shadowRoot.appendChild(styleElement); fetchCSS().then((css) => (styleElement.textContent = css)); const container = document.createElement("div"); shadowRoot.appendChild(container); const root = ReactDOM.createRoot(container); root.render(); return () => { root.unmount(); rootDiv.remove(); }; } async function fetchCSS() { const cssUrl = new URL("./content.css", import.meta.url); const response = await fetch(cssUrl); const text = await response.text(); return response.ok ? text : Promise.reject(text); } ``` A plain `import "./content.css"` styles nothing in a content script. See [CSS, Sass, and Less](/docs/implementation-guide/css) for every route. ## Next steps * Start from the [React template](/docs/getting-started/templates) (`--template=react`) when you want a sidebar panel plus a content script. * Learn more about [TypeScript support](/docs/languages-and-frameworks/typescript). * Explore how Extension.js handles [Sass modules](/docs/languages-and-frameworks/sass). ## Video walkthrough [Extension.js: React HMR](https://www.youtube-nocookie.com/embed/Y5lJfxntH9k?rel=0) ## See the template run [Extension.js: Content React template](https://www.youtube-nocookie.com/embed/oGNhj9k4bNs?rel=0) # Sass and SCSS Modules in browser extensions Source: https://extension.js.org/docs/languages-and-frameworks/sass Scale browser extension styling with Sass variables, nesting, and SCSS Modules. Extension.js supports .scss, .sass, and .module variants via Rspack. Use Sass to scale browser extension styling with variables, nesting, and SCSS Modules while keeping a single build workflow. Extension.js supports `.scss` and `.sass`, plus SCSS module variants (`.module.scss`, `.module.sass`) through the Rspack-based style pipeline. ## When Sass is a good fit * Your design system already relies on Sass variables and mixins. * You need modular styles for component-driven extension UIs. * You want parity with existing Sass workflows in web applications. ## Template examples ### `new-sass` ![new-sass template screenshot](https://mintcdn.com/extensionjs/etcqPhDg4wwyPkcC/images/examples/newtab-sass/screenshot.png?fit=max\&auto=format\&n=etcqPhDg4wwyPkcC\&q=85\&s=f4951d5a05864f5475900bdcdd3f5f52) Start a new-tab extension with Sass support already configured. ```bash npm theme={null} npx extension@latest create my-extension --template=newtab-sass ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=newtab-sass ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=newtab-sass ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=newtab-sass ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=newtab-sass ``` Repository: [extension-js/templates/newtab-sass](https://github.com/extension-js/templates/tree/main/examples/newtab-sass) ## Usage with an existing extension Add Sass to an existing extension with the steps below. ### Installation Install the required dependency: ```bash npm theme={null} npm install -D sass ``` ```bash pnpm theme={null} pnpm add -D sass ``` ```bash yarn theme={null} yarn add -D sass ``` ```bash bun theme={null} bun add -d sass ``` ```bash deno theme={null} deno add -D npm:sass ``` ### Example usage in an HTML file In extension pages (popup/options/new tab), import Sass from your entry script: ```html theme={null} New Extension

Hello, Extension.

``` ```ts theme={null} import "./styles/globals.scss"; console.log("Sass loaded"); ``` ## Sass modules Scope styles locally with Sass modules, just like CSS Modules. Use `.module.scss` or `.module.sass` to activate scoping and prevent naming conflicts in your stylesheets. ### `content-sass-modules` ![content-sass-modules template screenshot](https://mintcdn.com/extensionjs/VCnDd7fX2Nza24SE/images/examples/content-sass-modules/screenshot.png?fit=max\&auto=format\&n=VCnDd7fX2Nza24SE\&q=85\&s=db5f350d56fd869acc019bda11ffb989) Use Sass modules in content scripts when you need scoped styling for injected UI. ```bash npm theme={null} npx extension@latest create my-extension --template=content-sass-modules ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=content-sass-modules ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=content-sass-modules ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=content-sass-modules ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=content-sass-modules ``` Repository: [extension-js/templates/content-sass-modules](https://github.com/extension-js/templates/tree/main/examples/content-sass-modules) ## Using Sass modules in an existing extension To enable Sass modules, rename your Sass file to include `.module.scss` or `.module.sass`. This automatically scopes the styles to your component. ```diff theme={null} - button.scss + button.module.scss ``` ### Example usage After renaming your Sass file, import it into your script: ```ts theme={null} import styles from "./styles/button.module.scss"; const element = document.createElement("h1"); element.className = styles.primaryColor; element.innerText = "Hello, Extension!"; document.body.appendChild(element); ``` In the Sass file: ```scss theme={null} /* styles/button.module.scss */ $primary-color: #64ff00; :export { primaryColor: $primary-color; } ``` ## React/Preact example usage Import the Sass module into your React or Preact component, and use the scoped class names: ```jsx theme={null} import styles from "./styles/button.module.scss"; export default function MyComponent() { return

Hello, Extension!

; } ``` ## Vue example usage In Vue SFCs, prefer module styles with `lang="scss"`: ```vue theme={null} ``` ## Svelte example usage In Svelte, import Sass module mappings and apply classes: ```svelte theme={null}

Hello, Extension!

``` ## Behavior notes * In extension pages, `.module.scss` and `.module.sass` export class maps for JS/TS imports. * In content scripts, Extension.js emits Sass as CSS assets without JavaScript class-name mappings. * If the `sass` package is not installed, Extension.js warns and copies the raw Sass source into the output CSS, so those surfaces render unstyled until you install it yourself. ## Next steps * Learn more about [CSS Modules](/docs/languages-and-frameworks/css-modules). * Ensure stylesheet quality with [Stylelint](/docs/integrations/stylelint). ## Video walkthrough [Extension.js: New Tab Sass template](https://www.youtube-nocookie.com/embed/bUWLBJeWzpc?rel=0) # Svelte for browser extensions Source: https://extension.js.org/docs/languages-and-frameworks/svelte Build extension UIs with Svelte components. Extension.js auto-configures .svelte file resolution, loader setup, and aliases from your dependencies. Build extension UIs with Svelte components while keeping Extension.js in charge of the framework wiring. Extension.js detects Svelte from your project dependencies and configures `.svelte` resolution, loader setup, and Svelte client aliases automatically. ## When Svelte is a good fit * You want a smaller runtime for popup, options, sidebar, or new-tab UIs. * You prefer component-first authoring with concise syntax. * You want a framework option that works for both extension pages and content-script UI mounts. ## Template examples ### `new-svelte` ![new-svelte template screenshot](https://mintcdn.com/extensionjs/etcqPhDg4wwyPkcC/images/examples/newtab-svelte/screenshot.png?fit=max\&auto=format\&n=etcqPhDg4wwyPkcC\&q=85\&s=5d530239aa0e90e3956a0c6d857efba4) Use the Svelte starter when you want a framework-first extension UI with minimal setup. ```bash npm theme={null} npx extension@latest create my-extension --template=newtab-svelte ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=newtab-svelte ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=newtab-svelte ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=newtab-svelte ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=newtab-svelte ``` Repository: [extension-js/templates/newtab-svelte](https://github.com/extension-js/templates/tree/main/examples/newtab-svelte) ### `content-svelte` ![content-svelte template screenshot](https://mintcdn.com/extensionjs/VCnDd7fX2Nza24SE/images/examples/content-svelte/screenshot.png?fit=max\&auto=format\&n=VCnDd7fX2Nza24SE\&q=85\&s=e22068b8e59673c5abd68cfbec2eda46) Inject Svelte components into web pages through content scripts. ```bash npm theme={null} npx extension@latest create my-extension --template=content-svelte ``` ```bash pnpm theme={null} pnpx extension@latest create my-extension --template=content-svelte ``` ```bash yarn 2+ theme={null} yarn dlx extension@latest create my-extension --template=content-svelte ``` ```bash bun theme={null} bunx extension@latest create my-extension --template=content-svelte ``` ```bash deno theme={null} deno run -A npm:extension@latest create my-extension --template=content-svelte ``` Repository: [extension-js/templates/content-svelte](https://github.com/extension-js/templates/tree/main/examples/content-svelte) ## Usage with an existing extension Install Svelte: ```bash npm theme={null} npm install svelte ``` ```bash pnpm theme={null} pnpm add svelte ``` ```bash yarn theme={null} yarn add svelte ``` ```bash bun theme={null} bun add svelte ``` ```bash deno theme={null} deno add npm:svelte ``` For explicit setup in an existing project, install the Svelte loader too: ```bash npm theme={null} npm install -D svelte-loader typescript ``` ```bash pnpm theme={null} pnpm add -D svelte-loader typescript ``` ```bash yarn theme={null} yarn add -D svelte-loader typescript ``` ```bash bun theme={null} bun add -d svelte-loader typescript ``` ```bash deno theme={null} deno add -D npm:svelte-loader npm:typescript ``` When the optional `svelte-loader` package is missing, the build error names the exact version that matches the bundled toolchain. The install command in the error is phrased for the package manager that your project uses. ## Development behavior When Extension.js detects Svelte, it: * Enables `.svelte` file resolution. * Configures the Svelte loader in the JS framework pipeline, with hot reload enabled in development so edited components update without a full page reload. * Applies Svelte client aliases (for example, `svelte`, `svelte/store`, and `svelte/reactivity`). If your project lacks optional tooling, Extension.js warns with the exact install command instead of installing it for you. Restart. ## Usage examples ### In an extension page ```html theme={null} Svelte Extension
``` ```ts theme={null} import {mount} from "svelte"; import App from "./App.svelte"; mount(App, { target: document.getElementById("app")!, }); ``` Extension.js targets Svelte 5. The Svelte 4 class API (`new App(...)` and `app.$destroy()`) throws `component_api_invalid_new` on the version the templates install. ### In a `content_script` file For content scripts, create a mount node and return a cleanup function from your default export. This lets Extension.js remount safely in development: ```ts theme={null} import {mount, unmount} from "svelte"; import App from "./App.svelte"; export default function main() { const target = document.createElement("div"); target.id = "extension-root"; document.body.appendChild(target); const app = mount(App, {target}); return () => { unmount(app); target.remove(); }; } ``` From the release after 4.1.39, a component ` ``` ### In a `content_script` file For content scripts, mount a Vue app inside a shadow root, and load the stylesheet into that root: ```ts theme={null} import { createApp } from "vue"; import App from "./App.vue"; export default function initial() { const rootDiv = document.createElement("div"); rootDiv.setAttribute("data-extension-root", "true"); rootDiv.style.cssText = "all: initial !important"; document.body.appendChild(rootDiv); const shadowRoot = rootDiv.attachShadow({ mode: "open" }); const styleElement = document.createElement("style"); shadowRoot.appendChild(styleElement); fetchCSS().then((css) => (styleElement.textContent = css)); const container = document.createElement("div"); shadowRoot.appendChild(container); const app = createApp(App); app.mount(container); return () => { app.unmount(); rootDiv.remove(); }; } async function fetchCSS() { const cssUrl = new URL("./content.css", import.meta.url); const response = await fetch(cssUrl); const text = await response.text(); return response.ok ? text : Promise.reject(text); } ``` A plain `import "./content.css"` styles nothing in a content script. See [CSS, Sass, and Less](/docs/implementation-guide/css) for every route. From the release after 4.1.39, a component `