@adguard/tswebextension

中文文档
6.0.1发布于 2026/10/16GPL-3.0-onlyTypeScriptES Module近 30 天下载 1786

This is a TypeScript library that implements AdGuard's extension API

原始使用文档
文档目录16 节
  1. Browser compatibility
  2. Install
  3. Usage
  4. CLI
  5. Side effects
  6. API
  7. configuration
  8. TsWebExtension
  9. Utilities
  10. getFilterName
  11. isUserScriptsApiEnabled
  12. Filtering Log API (MV2 only)
  13. events
  14. properties
  15. methods
  16. Documentation

TSWebExtension

TypeScript library that wraps webextension api for tsurlfilter library.

Table of content:

Browser compatibility

BrowserVersion
Chromium-based browsers MV2106
Chromium-based browsers MV3121
Firefox78
Firefox Mobile113

Install

pnpm add @adguard/tswebextension

Usage

You can find examples in packages/examples/tswebextension-*

Note:

Before running compiled app, load the web accessible resources for redirect rules

via built-in cli:

tswebextension war [path]

or integrate loading in your build pipeline:

import { copyWar, DEFAULT_WAR_PATH } from '@adguard/tswebextension/cli';

const build = async () => {
    ...
    await copyWar(DEFAULT_WAR_PATH);
    ...
};

If path is not defined, the resources will be loaded to build/war relative to your current working directory by default

CLI

The console interface provides useful tools for building extensions.

Usage: tswebextension [options] [command]

CLI to some development utils

Options:
    -V, --version     output the version number
    -h, --help        display help for command

Commands:
    war [path]        Downloads web accessible resources for redirect rules
    help [command]    display help for command

Side effects

In this project, the sideEffects field is defined as follows in the package.json file:

"sideEffects": [
    "dist/assistant-inject.js",
    "dist/content-script.js",
    "dist/content-script.mv3.js",
    "dist/gpc.mv3.js",
    "dist/hide-document-referrer.mv3.js"
]

This configuration indicates that the specified files have side effects and should not be tree-shaken by the bundler. These files will modifying the global scope, which are essential for the correct functioning of the application.

By explicitly listing these files, we ensure that they are included in the final bundle, even if they do not have any direct imports or exports that are used elsewhere in the codebase.

In the content script, we need access to @adguard/assistant only when the user clicks 'block ad manually'. Therefore, we marked files with @adguard/assistant as side effects. We also added a required field to the configuration object to ensure the assistant is bundled inside the final extension, allowing tswebextension to load it on-demand.

Same approach with dynamic injecting we use for stealth options GPC and Hide Document Referrer. Handlers for these options will dynamically register content scripts via scripting.registerContentScript.

API

The main idea of the library is to provide a common interface for different browsers and manifest versions via Configuration object.

TsWebExtension class provides a set of methods for filtering content from the extension's background context.

MV2 submodule also provides a set of methods for filtering log management.

configuration

type: Configuration

Configuration object.

TSWEBEXTENSION_VERSION

type: string

Version of the library.

EXTENDED_CSS_VERSION

type: string

Version of the extended css module, used in current library version.

filters (MV2 only)

type: FilterMV2[]

List of filters.

filterId

type: number

Filter identifier.

content

type: Uint8Array[]

AGTree byte buffer chunks.

trusted

type: boolean

Determines if filter list js rules should be executed.

staticFiltersIds (MV3 only)

type: number[]

List of static filters ids.

customFilters (MV3 only)

type: CustomFilterMV3[]

List of custom filters that can be added/edited/deleted by the user.

filterId

type: number

Filter identifier.

content

type: string

Converted filter list content (rules converted to AdGuard format).

conversionData

type: ConversionData

Conversion data from FilterList.getConversionData(), containing:

  • originals: Array of original rule texts that were converted
  • conversions: Map of line start offsets in converted content to indexes in the originals array

filtersPath (MV3 only)

type: string

Path to the filter list file.

rulesetsPath (MV3 only)

type: string

Path to directory with converted rule sets.

declarativeLogEnabled (MV3 only)

type: boolean

Enables matching declarative rules for filtering log.

allowlist

type: string[]

List of hostnames or domains of sites, which should be excluded from blocking or which should be included in blocking depending on the value of allowlistInverted setting value.

trustedDomains

type: string[]

List of domain names of sites, which should be temporary excluded from document blocking.

userrules (MV2)

content

type: string

Converted filter list content (rules converted to AdGuard format).

conversionData

type: ConversionData

Conversion data from FilterList.getConversionData(), containing:

  • originals: Array of original rule texts that were converted
  • conversions: Map of line start offsets in converted content to indexes in the originals array

userrules (MV3)

content

type: string

Converted filter list content (rules converted to AdGuard format).

conversionData

type: ConversionData

Conversion data from FilterList.getConversionData(), containing:

  • originals: Array of original rule texts that were converted
  • conversions: Map of line start offsets in converted content to indexes in the originals array

verbose (deprecated)

type: boolean | undefined

Optional flag responsible for logging. Defaults to true. Will be removed in the next minor version.

logLevel

type: string | undefined

Optional flag that sets logging level, defaults to 'error'. Available levels: 'error', 'warn', 'info', 'debug', 'trace'.

settings

type: SettingsConfig

Settings configuration object.

allowlistInverted

type: boolean

If this flag is true, the application will work ONLY with domains from the allowlist, otherwise it will work everywhere EXCLUDING domains from the list.

allowlistEnabled

type: boolean

Flag specifying allowlist enable state. We don't use allowlist array length condition for calculate enable state, because it's not cover case with empty list in inverted mode.

collectStats

type: boolean

Enables css hits counter if true.

debugScriptlets

Optional, type: boolean

Defaults to false. Enables scriptlets logging in console if true.

stealthModeEnabled

type: boolean

Enables stealth mode if true.

filteringEnabled

type: boolean

Enables filtering if true.

documentBlockingPageUrl

type: string

Redirect url for blocking rules with $document modifier.

assistantUrl

type: string

Path to the assembled @adguard/assistant module. Necessary for lazy on-demand loading of the assistant.

gpcScriptUrl (MV3 only)

type: string

Path to the content script that set GPC Signal. Necessary for Do Not Track stealth option.

hideDocumentReferrerScriptUrl (MV3 only)

type: string

Path to the content script that hides the document referrer. Necessary for Hide Search Queries stealth option.

stealthConfig

type: StealthConfig

Stealth mode configuration object.

selfDestructFirstPartyCookies

type: boolean

Should the application set a fixed lifetime from selfDestructFirstPartyCookiesTime for first-party cookies.

selfDestructFirstPartyCookiesTime

type: number

Time in minutes to delete first-party cookies.

selfDestructThirdPartyCookies

type: boolean

Should the application set a fixed lifetime from selfDestructThirdPartyCookiesTime for third-party cookies.

selfDestructThirdPartyCookiesTime

type: number

Time in minutes to delete third-party cookies.

hideReferrer

type: boolean

Should the application hide the origin referrer in third-party requests by replacing the referrer url with the request url.

hideSearchQueries

type: boolean

Should the application hide the original referrer from the search page containing the search query in third-party queries, replacing the referrer url with the request url.

blockChromeClientData

type: boolean

For Google Chrome, it removes the 'X-Client-Data' header from the requests, which contains information about the browser version and modifications.

sendDoNotTrack

type: boolean

Includes HTTP headers 'DNT' and 'Sec-GPC' in all requests.

Read more about DNT: https://en.wikipedia.org/wiki/Do_Not_Track.

Read more about GPC: https://globalprivacycontrol.org.

blockWebRTC

type: boolean

Blocks the possibility of leaking your IP address through WebRTC, even if you use a proxy server or VPN.

TsWebExtension

Properties

configuration

type: ConfigurationMV2Context | ConfigurationMV3Context

Configuration context with an omitted array of rule and domain strings loaded in the filter engine.

It is used to reduce memory consumption when storing configuration data in memory.

onFilteringLogEvent

type: EventChannel<FilteringLogEvent>

Event channel for filtering log events.

isStarted

type: boolean

Is app started.

Methods

initStorage()

type: () => Promise<void>

Initialize app persistent data. This method called as soon as possible and allows access to the actual context before the app is started.

start()

type: (configuration: TConfiguration) => Promise<TConfigurationResult>

Starts the app.

Also updates webRTC privacy.network settings on demand and flushes browser in-memory request cache.

configure()

type: (configuration: TConfiguration) => Promise<TConfigurationResult>

Updates the configuration.

Also updates webRTC privacy.network settings on demand and flushes browser in-memory request cache.

MV3 Error Handling: When using Manifest V3, the ConfigurationResult returned by configure() and start() contains multiple fields with errors and limitations that must be checked:

  • staticFiltersStatus.errors: Array of FailedEnableRulesetsError instances if browser.declarativeNetRequest.updateEnabledRulesets fails. The browser does not update or enable any rulesets if any single ruleset is not found.
  • dynamicRules.errors: Array of conversion errors that occurred during dynamic rules conversion (custom filters, user rules, allowlist).
  • dynamicRules.limitations: Array of limitation errors if dynamic rules were truncated due to browser limits.

These errors are not thrown but returned in the result. You must check these fields for critical errors and handle them appropriately (e.g., throw, log, notify the user).

const result = await tsWebExtension.configure(configuration);

// Check static filter errors
if (result.staticFiltersStatus.errors.length > 0) {
    console.error('Failed to enable rulesets:', result.staticFiltersStatus.errors);
}

// Check dynamic rules errors and limitations
if (result.dynamicRules) {
    if (result.dynamicRules.errors.length > 0) {
        console.error('Dynamic rules conversion errors:', result.dynamicRules.errors);
    }
    if (result.dynamicRules.limitations.length > 0) {
        console.warn('Dynamic rules were truncated:', result.dynamicRules.limitations);
    }
}
stop()

type: () => Promise<void>

Stops the app.

openAssistant()

type: (tabId: number) => void

Opens the assistant in the specified tab.

closeAssistant()

type: (tabId: number) => void

getRulesCount()

type: () => number

Returns number of active rules.

retrieveRuleNode

type: (filterId: number, ruleIndex: number): AnyRule | null

Retrieves rule node from engine by filter id and rule index.

getMessageHandler()

type: () => MessageHandlerMV2 | MessageHandlerMV3

Returns a message handler that will listen to internal messages, for example: message for get computed css for content-script.

setFilteringEnabled() (MV2 only)

type: (isFilteringEnabled: boolean) => Promise<void>

Updates filteringEnabled configuration value without re-initialization of engine.

Also updates webRTC privacy.network settings on demand and flushes browser in-memory request cache.

Throws error if configuration is not set.

setCollectHitStats() (MV2 only)

type: (isCollectStats: boolean) => void

Updates collectStats configuration value without re-initialization of engine.

Throws error if configuration is not set.

setDebugScriptlets()

type: (isDebugScriptlets: boolean) => void

Updates debugScriptlets configuration value without re-initialization of engine.

Throws error if configuration is not set.

setStealthModeEnabled() (MV2 only)

type: (value: isStealthModeEnabled) => Promise<void>

Updates stealthModeEnabled configuration value without re-initialization of engine.

Also updates webRTC privacy.network settings on demand.

Throws error if configuration is not set.

setSelfDestructFirstPartyCookies() (MV2 only)

type: (isSelfDestructFirstPartyCookies: boolean) => void

Updates selfDestructFirstPartyCookies stealth config value without re-initialization of engine.

Throws error if configuration is not set.

setSelfDestructThirdPartyCookies() (MV2 only)

type: (isSelfDestructThirdPartyCookies: boolean) => void

Updates selfDestructThirdPartyCookies stealth config value without re-initialization of engine.

Throws error if configuration is not set.

setSelfDestructFirstPartyCookiesTime() (MV2 only)

type: (selfDestructFirstPartyCookiesTime: number) => void

Updates selfDestructFirstPartyCookiesTime stealth config value without re-initialization of engine.

Throws error if configuration is not set.

setSelfDestructThirdPartyCookiesTime() (MV2 only)

type: (selfDestructThirdPartyCookiesTime: number) => void

Updates selfDestructThirdPartyCookiesTime stealth config value without re-initialization of engine.

Throws error if configuration is not set.

setHideReferrer() (MV2 only)

type: (isHideReferrer: boolean) => void

Updates hideReferrer stealth config value without re-initialization of engine.

Throws error if configuration is not set.

setHideSearchQueries() (MV2 only)

type: (isHideSearchQueries: boolean) => void

Updates hideSearchQueries stealth config value without re-initialization of engine.

Throws error if configuration is not set.

setBlockChromeClientData() (MV2 only)

type: (isBlockChromeClientData: boolean) => void

Updates blockChromeClientData stealth config value without re-initialization of engine.

Throws error if configuration is not set.

setSendDoNotTrack() (MV2 only)

type: (isSendDoNotTrack: boolean) => void

Updates sendDoNotTrack stealth config value without re-initialization of engine.

Throws error if configuration is not set.

setBlockWebRTC() (MV2 only)

type: (isBlockWebRTC: boolean) => Promise<void>

Updates blockWebRTC stealth config value without re-initialization of engine.

Also updates webRTC privacy.network settings on demand.

Throws error if configuration is not set.

Utilities

Separate entry point for utilities that can be used in the extension.

They can be imported like this:

import { getFilterName, isUserScriptsApiEnabled } from '@adguard/tswebextension/mv3/utils';

getFilterName

type: (filterId: number) => string

For the specified filter identifier the filter file name is generated with an extension, in which the text filter rules should be saved.

isUserScriptsApiEnabled

type: () => boolean

Returns true if user scripts API is available and enabled, false otherwise.

Filtering Log API (MV2 only)

Provides a set of methods for filtering log events management.

events

sendRequest

type: SendRequestEvent

Dispatched on request sending.

tabReload

type: TabReloadEvent

Dispatched on tab reload.

applyBasicRule

type: ApplyBasicRuleEvent

Dispatched on request block or allowlist rule matching.

applyCosmeticRule

type: ApplyCosmeticRuleEvent

Dispatched on elemhide, css or html rule applying.

applyCspRule

type: ApplyCspRuleEvent

Dispatched on csp rule applying.

receiveResponse

type: ReceiveResponseEvent

Dispatched on response receiving.

type: CookieEvent

Dispatched on cookie removing or modifying.

removeHeader

type: RemoveHeaderEvent

Dispatched on request or response header removing.

removeParam

type: RemoveParamEvent

Dispatched on request or response param removing.

replaceRuleApply

type: ReplaceRuleApplyEvent

Dispatched on replace rule applying.

contentFilteringStart

type: ContentFilteringStartEvent

Dispatched on content filtering start.

contentFilteringFinish

type: ContentFilteringFinishEvent

Dispatched on content filtering end.

stealthAction

type: StealthActionEvent

Dispatched on stealth action.

stealthAllowlistAction

type: StealthAllowlistActionEvent

Dispatched on preventing stealth action with $stealth rule.

JsInject

type: JsInjectEvent

Dispatched on js inject into page context.

properties

onLogEvent

type: EventChannel<FilteringLogEvent>

Event channel for filtering log events.

methods

addEventListener()

type:

<T extends FilteringEventType>(type: T, listener: FilteringLogListener<ExtractedFilteringLogEvent<T>>) => void

Registers a listener for the specified filtering event type.

publishEvent()

type:

<T extends FilteringLogEvent>(event: T) => void

Dispatch the specified filtering event.

Documentation

版本与发布记录

@adguard/tswebextension 共发布 186 个版本,首次发布于 2022/06/17;过去 12 个月发布了 23 个版本。

版本发布日期距今
6.0.1latest2026/10/1623 天前
6.0.02026/09/291 个月前
6.0.0-beta.0beta2026/09/291 个月前
5.0.32026/08/252 个月前
5.0.22026/08/252 个月前
5.0.12026/08/212 个月前

其他发布通道:alpha → 3.1.0-alpha.4,beta → 6.0.0-beta.0。

关于 @adguard/tswebextension 的常见问题

@adguard/tswebextension 是什么?

This is a TypeScript library that implements AdGuard's extension API

如何安装 @adguard/tswebextension?

在项目目录运行 npm install @adguard/tswebextension,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 tswebextension,可以用 npx tswebextension 直接运行。

@adguard/tswebextension 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@adguard/tswebextension 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@adguard/tswebextension 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@adguard/tswebextension 可以商用吗?

@adguard/tswebextension 使用 GPL-3.0-only 许可。强 Copyleft:分发包含该代码的软件时,整个作品需以 GPL-3.0 兼容许可开源,并附带专利与反锁定条款。仅内部使用不触发此义务。以上为概括,不构成法律意见,请以许可原文为准。

@adguard/tswebextension 的下载量有多少?

根据 npm 官方下载统计,@adguard/tswebextension 在 2026/10/05 – 2026/11/03 这 30 天内被下载 1,786 次,日均约 60 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@adguard/tswebextension 还在维护吗?

最新版本 6.0.1 发布于 2026/10/16(23 天前);至今共发布 186 个版本,其中过去 12 个月发布了 23 个;首次发布于 2022/06/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。