> ## Documentation Index
> Fetch the complete documentation index at: https://extension.js.org/llms.txt
> Use this file to discover all available pages before exploring further.

> ## 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/<browser>, 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.

# Inject scripts at runtime

> Inject scripts into pages with manifest content_scripts, chrome.scripting.executeScript, or registerContentScripts, plus the permissions and errors for each.

A browser extension can run code inside a web page in three ways. A manifest `content_scripts` entry runs on every page that matches a pattern. `chrome.scripting.executeScript` runs one script in one tab when you call it. `chrome.scripting.registerContentScripts` registers a content script at runtime and keeps it registered. This page explains when each one runs, which permission it needs, and how the browsers differ. It also lists the console lines that injection failures print and where the file goes in an Extension.js project.

## The three ways to run code in a page

**Manifest `content_scripts`.** A static declaration in `manifest.json`. The browser injects the listed `js` and `css` files into every page that matches `matches`, at the time set by `run_at`. Extension.js compiles each entry and wraps it for HMR, see [Content scripts](https://extension.js.org/docs/implementation-guide/content-scripts.md).

**`chrome.scripting.executeScript`.** A one-off call from the service worker or another extension page. It targets one tab and runs either `files` (paths inside the extension) or `func` (a function serialized into the page, with optional `args`). It needs the `scripting` permission plus access to the tab, from `activeTab` after a user gesture or from a matching `host_permissions` pattern.

**`chrome.scripting.registerContentScripts`.** A dynamic registration with the same shape as a manifest entry (`id`, `matches`, `js`, `css`, `runAt`, `world`). The browser injects it into pages that match from that moment on, and the registration persists across browser restarts by default. It needs the `scripting` permission and `host_permissions` that cover `matches`, because `activeTab` does not apply to future pages.

| Property | Manifest `content_scripts` | `executeScript` | `registerContentScripts` |
| - | - | - | - |
| When it runs | Every matching page, on load | Once, when you call it | Every matching page, from registration |
| Permission needed | `matches` in the manifest | `scripting` plus `activeTab` or host | `scripting` plus host permissions |
| Survives a browser restart | Yes | No, the script ran once | Yes, unless `persistAcrossSessions` is false |
| Can target `world: "MAIN"` | Yes, Chrome 111, Firefox 128, Safari 18 | Yes, Chrome 95, Firefox 128, Safari 15.4 | Yes, Chrome 102, Firefox 128, Safari 16.4 |
| Firefox support (MV3) | Yes | Yes | Yes |

Use the manifest entry when the feature belongs on a known set of sites. Use `executeScript` when the user triggers the feature, for example from a toolbar click. Use `registerContentScripts` when the set of sites is decided at runtime, for example from a settings page.

## Manifest snippet

The `scripting` permission unlocks both runtime APIs. `activeTab` covers the tab the user clicked in, and `host_permissions` covers every page that matches, which dynamic registration requires:

```json theme={null}
{
  "manifest_version": 3,
  "name": "Inject on demand",
  "version": "1.0.0",
  "permissions": ["scripting", "activeTab"],
  "host_permissions": ["https://example.com/*"],
  "action": { "default_title": "Inject" },
  "background": { "service_worker": "background.js" }
}
```

Chromium and Firefox both read this block as written, so it needs no browser prefix. A manifest content script with `world: "MAIN"` needs no prefix either on Chrome 111, Firefox 128, and Safari 18 or later. Use `chromium:world` with an isolated-world fallback only if you must support older browsers, as shown in [Content scripts](https://extension.js.org/docs/implementation-guide/content-scripts.md).

The runtime calls that match this manifest:

```ts theme={null}
// One-off, after the user clicks the action (activeTab).
chrome.action.onClicked.addListener(async (tab) => {
  await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: ["scripts/highlight.js"],
  });
});

// Persistent, covered by host_permissions.
await chrome.scripting.registerContentScripts([
  {
    id: "highlight",
    matches: ["https://example.com/*"],
    js: ["scripts/highlight.js"],
    runAt: "document_idle",
  },
]);
```

## Change a registration

Calling `registerContentScripts` again with an id that is already registered rejects in both browsers. It never replaces the first registration, which stays in place.

* Chrome: `Duplicate script ID 'highlight'`
* Firefox: `Content script with id "highlight" is already registered`

To change an existing registration, call `updateContentScripts` with the same id. The next navigation injects the new file. An unknown id rejects in both browsers.

```ts theme={null}
await chrome.scripting.updateContentScripts([
  {
    id: "highlight",
    js: ["scripts/highlight-v2.js"],
    persistAcrossSessions: true,
  },
]);
```

Pass `persistAcrossSessions: true` again in the update. In Chrome 155, an update that omits it resets the value from `true` to `false`. Firefox 158 keeps it `true`. Measured with Extension.js 4.1.33.

## Per-browser differences

| Capability | Chromium | Firefox | Safari |
| - | - | - | - |
| `executeScript` `world` | `ISOLATED` (default) or `MAIN`, from Chrome 95 | `ISOLATED` (default) or `MAIN`, from Firefox 128 | `MAIN` from Safari 15.4 |
| `registerContentScripts` | Supported | Supported in MV3 | Not covered by these docs |
| `insertCSS` `origin` | `AUTHOR` (default) or `USER` | `AUTHOR` (default) or `USER` | Not covered by these docs |
| Before any script runs | Access follows the manifest | Access follows the manifest | You grant website access per site after you enable the extension |

On Safari, enabling the extension is not enough. Until you grant website access, no content script runs, and the same applies to scripts you inject at runtime. See [Safari](https://extension.js.org/docs/browsers/safari.md) for the enable and grant steps.

From the release after 4.1.39, `chrome.scripting` and `browser.scripting` both work on a Firefox Manifest V2 background page, in `dev` and in a production build. Each keeps its own calling style: `chrome.scripting` answers a callback, and `browser.scripting` returns a promise.

## Console lines you will see

Copy the line that you see into search. Each one maps to one cause.

`Cannot access contents of url "https://example.com/". Extension manifest must request permission to access this host.`
The tab is outside your host permissions and `activeTab` was not granted for it. Add the host to `host_permissions`, or call `executeScript` from a handler that runs after a user gesture on the tab.

`Could not load file: 'scripts/highlight.ts'.`
The `executeScript` or `registerContentScripts` call names a source path. Extension.js compiles `scripts/highlight.ts` to `scripts/highlight.js`, so inject the emitted `.js` path.

`Failed to load resource: net::ERR_FILE_NOT_FOUND`
A `chrome-extension://` URL that ends in `.ts` (or another path that never reached `dist/`). Same fix: reference the emitted `.js` file, then confirm it exists under `dist/<browser>/scripts/`.

`NS_ERROR_CONTENT_BLOCKED`
The Firefox form of the same missing-file error on a `moz-extension://` URL. Inject the emitted `.js` path.

`Cannot access a chrome:// URL`
Browser pages cannot be scripted. Test on a normal `https://` page.

`The extensions gallery cannot be scripted.`
The Chrome Web Store is off limits to every extension. Test on another page.

`This page cannot be scripted due to an ExtensionsSettings policy.`
A managed browser blocks your extension on this host. Test on a host that the policy allows, or on a profile that the policy does not manage.

## The Extension.js way

Put runtime-injected files in the `scripts/` special folder. The rules are short:

* `scripts/` lives beside `package.json` at the project root, not inside `src/`. A nested `src/scripts/` is a plain folder.
* Every file there compiles to `.js` and lands at `dist/<browser>/scripts/<name>.js`.
* Reference the emitted path in your `files` or `js` array. A `.ts` path builds fine but 404s in the browser.
* When a runtime literal names a `.ts` source, the build prints a warning with the emitted path to use.
* The file follows the content script contract: `export default` a synchronous function that returns an optional cleanup.

See [Special folders](https://extension.js.org/docs/features/special-folders.md) for the full folder contract.

During `extension dev`, scripts that you inject with `executeScript` from `scripts/` are replayed on edit, so the injected code updates live the way declarative `content_scripts` do. See [Reload and HMR](https://extension.js.org/docs/features/reload-and-hmr.md).

From the release after 4.1.39, `executeScript` with a `scripts/` file resolves with the value of the file's last expression, as a native file does. This holds on Chrome and Firefox. A value that the browser cannot clone, such as a DOM node or a function, gives no value.

A background script can call `registerContentScripts` as it starts. From the release after 4.1.39, `extension dev` holds the first page for a bounded time until those registrations answer. See [`dev`](https://extension.js.org/docs/commands/dev#the-first-page-waits-for-boot-registrations).

### Run a `scripts/` file in the MAIN world

Pass `world: "MAIN"` in the call, and the build compiles that `scripts/` file for the page's own world. Needs the release after 4.1.39.

```ts theme={null}
await chrome.scripting.registerContentScripts([
  {
    id: "hook",
    matches: ["https://example.com/*"],
    js: ["/scripts/hook.js"],
    runAt: "document_start",
    world: "MAIN",
  },
]);
```

* The build finds the call in the background, in extension pages, and in the local modules that they import.
* The search follows build aliases, `tsconfig.json` paths, and linked workspace packages. It skips packages installed under `node_modules`.
* `executeScript` with `files` and `world: "MAIN"` gets the same treatment.
* In development, the file carries no HMR runtime and no dev instrumentation, so neither runs on the host page.
* A production build leaves no `__EXTENSIONJS_*` global on the page, even when the file imports other `scripts/` modules.
* A dynamic `import()` in the file loads its chunk, also at `document_start`.
* On Firefox, the file resolves its imported assets and chunks from your `moz-extension://` origin.
* A production build hands the file that origin without writing it into the page's DOM.

That hand-off covers the build's own plumbing only. The page can read any extension URL that your script places in the DOM, and on Firefox that URL identifies the install. See the MAIN world notes in [Content scripts](https://extension.js.org/docs/implementation-guide/content-scripts.md) for the cases and the fix.

Write the path and `world: "MAIN"` as literals in the call. A `const` in the same file works too, and so does an exported `const` that the file imports. The build does not detect a call that is built from another value. When you add or remove a call during a session, `extension dev` restarts by itself to build the file for its new world. If the session cannot restart, it prints a warning that asks for a restart.

### Register one file in both worlds

Chromium injects one file path once per frame. A file that you register in both worlds under one path runs in the isolated world alone. The two worlds also need different builds.

From the release after 4.1.39, the build covers this case. When your source registers a `scripts/` file in the MAIN world and in the isolated world, the build emits two files:

* `scripts/<name>.js` is the isolated world build.
* `scripts/<name>.extjs-main-world.js` is the MAIN world build.

Keep the path `/scripts/<name>.js` in every call. The build routes a `world: "MAIN"` call to the second file, and `getRegisteredContentScripts` answers with the name that you wrote. If your project already has a file with that second name, your file wins and the build makes no copy.

A file that `registerContentScripts` places in the MAIN world only gets the second file too. The browser keeps a registered path across sessions, so that path stays a MAIN world build.

The build reads the world from the call. It reads a literal, a `const`, a choice between the two literals, a spread of a literal object, and a `.map()` over a literal list. A call with no `world` is an isolated one.

The build cannot read a world that exists only when the call runs, such as a function parameter. It builds the file for the isolated world and prints a warning that names the call:

```text theme={null}
background.ts:12 names scripts/hook.js in a scripting call whose world is only known when the call runs.
CALL background.ts:12
FILE scripts/hook.js
It is treated as an isolated world script, so a call that runs with world: 'MAIN' puts the isolated world build on the page.
Write the world as 'MAIN' or 'ISOLATED' in the call, or as a choice between the two, and the build prepares the file for each world it names.
```

### Paths in an extension page

In an extension page, start the path at the root, as in `/scripts/hook.js`. Firefox resolves `scripts/hook.js` against the page, so the script never runs and no error is thrown. A build for a Firefox target prints a warning that names the path to write. From the release after 4.1.39, the warning also covers a file that `include` or `public/` copies into the output.

Scaffold a project that injects a `scripts/` entry at runtime:

```bash theme={null}
npx extension@latest create my-extension --template=special-folders-scripts
```

For the static path, start from the `content` template instead:

```bash theme={null}
npx extension@latest create my-extension --template=content
```

## See also

* [Content scripts](https://extension.js.org/docs/implementation-guide/content-scripts.md)
* [Permissions and host permissions](https://extension.js.org/docs/implementation-guide/permissions-and-host-permissions.md)
* [Special folders](https://extension.js.org/docs/features/special-folders.md)
* [Web-accessible resources](https://extension.js.org/docs/implementation-guide/web-accessible-resources.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.