> ## 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.

# Build an ad blocker

> Block ads and trackers in a browser extension with declarativeNetRequest static and dynamic rules, plus a badge that counts blocked requests.

Build an adblocker, also written ad blocker or content blocker, with the `declarativeNetRequest` API. You declare matching rules, and the browser blocks requests natively before they leave the network stack.

## What you build

| Piece | What it does |
| - | - |
| `rules.json` | Static block rules that ship with the extension |
| `background.js` | Adds and removes dynamic rules at runtime |
| Action badge | Shows how many requests the extension blocked on a page |

## Why MV3 replaced blocking webRequest

Manifest V2 ad blockers registered blocking `webRequest` listeners. Every request paused while extension JavaScript decided its fate. Manifest V3 removed that model for performance and privacy reasons. With `declarativeNetRequest`, the browser evaluates your rules itself. Your code never sits on the request path and never reads request contents to block them.

For proxy-style use cases, such as routing all traffic through another server, use the `proxy` API instead of request rules.

## Manifest

Block and allow rules need no host permissions. Redirect rules and header rules need host permissions for the affected sites.

```json manifest.json theme={null}
{
  "manifest_version": 3,
  "name": "My Ad Blocker",
  "version": "1.0.0",
  "permissions": ["declarativeNetRequest"],
  "declarative_net_request": {
    "rule_resources": [
      {
        "id": "ads",
        "enabled": true,
        "path": "rules.json"
      }
    ]
  },
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_title": "My Ad Blocker"
  }
}
```

Extension.js compiles the ruleset file that `rule_resources` references and emits it with the build output.

## Static rules

Static rules live in `rules.json` and load when the extension loads.

```json rules.json theme={null}
[
  {
    "id": 1,
    "priority": 1,
    "action": { "type": "block" },
    "condition": {
      "urlFilter": "||ads.example.com^",
      "resourceTypes": ["script", "image", "sub_frame", "xmlhttprequest"]
    }
  },
  {
    "id": 2,
    "priority": 1,
    "action": { "type": "block" },
    "condition": {
      "urlFilter": "||tracker.example.net^",
      "resourceTypes": ["script", "xmlhttprequest"]
    }
  }
]
```

The `||domain^` filter syntax matches a domain and all of its subdomains.

## Block a whole page

A rule that names `main_frame` in `resourceTypes` blocks the top-level navigation, not only the subresources:

```json rules.json theme={null}
{
  "id": 3,
  "priority": 1,
  "action": { "type": "block" },
  "condition": {
    "urlFilter": "||blocked.example.com^",
    "resourceTypes": ["main_frame"]
  }
}
```

The two browsers show different results, and both mean that the rule worked:

* **Chrome** replaces the tab with its own blocked page. It reads "This page has been blocked by an extension" with the code `ERR_BLOCKED_BY_CLIENT`. Nothing is logged to the console.
* **Firefox** cancels the navigation, and the tab keeps the page that it had before. There is no error page and no console entry.

Extension.js copies the rule file to `dist/<browser>/declarative_net_request/` and rewrites the manifest path, so reference it the same way the manifest above does.

> [!NOTE]
>
> The behavior in this section and the next was measured on Chrome 155 and
> Firefox 158 with Extension.js 4.1.33.

## Redirect a blocked page to a page in the extension

Replace the `block` action with a `redirect` to a page that ships with the extension:

```json rules.json theme={null}
{
  "id": 4,
  "priority": 1,
  "action": {
    "type": "redirect",
    "redirect": { "extensionPath": "/blocked.html" }
  },
  "condition": {
    "urlFilter": "||blocked.example.com^",
    "resourceTypes": ["main_frame"]
  }
}
```

Put the page at `public/blocked.html`. Extension.js copies `public/` to the output root, so `/blocked.html` resolves with no manifest entry for the page.

A redirect needs more permission than a block, and the two browsers differ:

* **Chrome** needs a host permission that covers the site. Without it the rule is a silent no-op: the page loads normally, the ruleset still reports enabled, and nothing reaches the console. Chrome does not need `web_accessible_resources` for a `main_frame` redirect to an extension page.
* **Firefox** needs the host permission and the page listed in `web_accessible_resources`. Without the `web_accessible_resources` entry the navigation fails with `NS_ERROR_DOM_BAD_URI` and the tab stays where it was. Without the host permission it is a silent no-op, like Chrome.

The `action` template builds Firefox as Manifest V2, where host permissions live in `permissions` and `web_accessible_resources` is a list of strings. A prefixed key replaces the plain key on its target, so the Firefox list repeats `declarativeNetRequest`. One manifest covers both browsers with [browser-specific fields](https://extension.js.org/docs/features/browser-specific-fields.md):

```json manifest.json theme={null}
{
  "permissions": ["declarativeNetRequest"],
  "host_permissions": ["*://blocked.example.com/*"],
  "firefox:permissions": ["declarativeNetRequest", "*://blocked.example.com/*"],
  "firefox:web_accessible_resources": ["blocked.html"]
}
```

If your project builds Firefox as Manifest V3 as well, drop the `firefox:` keys and use the object form, `[{ "resources": ["blocked.html"], "matches": ["<all_urls>"] }]`, under plain `web_accessible_resources`. Both browsers accept it.

## Dynamic rules

Use dynamic rules for filters that change at runtime, such as user-added blocklist entries. Remove a rule id before you re-add it, so updates stay idempotent.

```js background.js theme={null}
async function blockDomain(domain, ruleId) {
  await chrome.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: [ruleId],
    addRules: [
      {
        id: ruleId,
        priority: 1,
        action: { type: 'block' },
        condition: {
          urlFilter: `||${domain}^`,
          resourceTypes: ['script', 'image', 'xmlhttprequest']
        }
      }
    ]
  })
}

chrome.runtime.onInstalled.addListener(() => {
  blockDomain('annoying-banners.example', 1001)
})
```

Chrome caps static and dynamic rule counts. Check the current limits in the `declarativeNetRequest` reference before you ship large filter lists.

## Count blocked requests on the badge

One call turns the action badge into a per-tab counter of matched rules.

```js background.js theme={null}
chrome.declarativeNetRequest.setExtensionActionOptions({
  displayActionCountAsBadgeText: true
})
```

To read matched rules yourself with `getMatchedRules`, add the `declarativeNetRequestFeedback` permission.

## Run it

Before you edit `manifest.json`, know that manifest changes need a dev-server restart. See [Dev update behavior](https://extension.js.org/docs/workflows/dev-update-behavior.md).

```bash theme={null}
npx extension@latest dev ./my-ad-blocker --browser=chromium
```

Open a page that requests a blocked domain. The badge count rises as rules match.

## Firefox notes

* Firefox supports `declarativeNetRequest` in Manifest V3.
* Firefox does not support `setExtensionActionOptions`, so the badge counter is Chromium-only.
* Firefox still allows blocking `webRequest` in Manifest V3, which Chrome reserves for policy installs.
* Use [browser-specific manifest fields](https://extension.js.org/docs/features/browser-specific-fields.md) when the two targets diverge.

## Start from a template

The `action` template ships a background script plus a toolbar popup, a good base for a blocker UI.

```bash theme={null}
npx extension@latest create my-ad-blocker --template=action
```

Repository: [extension-js/templates/action](https://github.com/extension-js/templates/tree/main/examples/action)

## Best practices

* Keep static rules in `rules.json` and reserve dynamic rules for user choices.
* Give every dynamic rule a stable id, so removals stay predictable.
* Scope `resourceTypes` to what you block, not to every type.
* Prefer block and allow rules, which need no host permissions.
* Test rules against real pages before you publish filter updates.

## Next steps

* Observe traffic without blocking it in [Intercept network requests](https://extension.js.org/docs/workflows/intercept-network-requests.md).
* Audit your permission surface with the [Security checklist](https://extension.js.org/docs/workflows/security-checklist.md).
* Review [Manifest V3 concepts](https://extension.js.org/docs/concepts/manifest-v3.md) for the background model.


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