欢迎 What's new in Chrome extensions Get help with Chrome extensions API reference Samples
欢迎 What's new in Chrome extensions Get help with Chrome extensions API reference Samples

chrome.declarativeNetRequest

  • Description

    The chrome.declarativeNetRequest API is used to block or modify network requests by specifying declarative rules. This lets extensions modify network requests without intercepting them and viewing their content, thus providing more privacy.

  • Permissions
    declarativeNetRequest
    declarativeNetRequestWithHostAccess
    declarativeNetRequestFeedback
    host permissions
    One or more of these permissions triggers a warning.
  • Availability
    Chrome 84+

Manifest

Extensions must declare either the declarativeNetRequest or the declarativeNetRequestWithHostAccess (available since Chrome 96) permission in the extension manifest to use this API. The former allows extensions to block and upgrade requests without any host permissions. Host permissions are still required if the extension wants to redirect a request or modify headers on it. The declarativeNetRequestWithHostAccess permission always requires host permissions to the request URL and initiator to act on a request.

The declarativeNetRequestFeedback permission is required to access functions and events which return information on declarative rules matched.

To specify static Rulesets, extensions must also declare the "declarative_net_request" manifest key, which should be a dictionary with a single key called "rule_resources". It should be a list containing dictionaries of type Ruleset, as shown below.

{
"name": "My extension",
...

"declarative_net_request" : {
"rule_resources" : [{
"id": "ruleset_1",
"enabled": true,
"path": "rules_1.json"
}, {
"id": "ruleset_2",
"enabled": false,
"path": "rules_2.json"
}]
},
"permissions": [
"declarativeNetRequest",
"declarativeNetRequestFeedback",
],
"host_permissions": [
"http://www.blogger.com/*",
"http://*.google.com/*"
],
...
}

Rule Resources

An extension can specify up to MAX_NUMBER_OF_STATIC_RULESETS rulesets as part of the "rule_resources" manifest key. Only MAX_NUMBER_OF_ENABLED_STATIC_RULESETS of these rulesets can be enabled at a time, assuming static rule limits are not exceeded.

An extension is allowed to enable at least GUARANTEED_MINIMUM_STATIC_RULES static rules. Additional static rulesets may or may not be enabled depending on the available global static rule limit.

Note: Errors and warnings about invalid static rules are only displayed for unpacked extensions. Invalid static rules in packed extensions are ignored. It's therefore important to verify that your static rulesets are valid by testing with an unpacked version of your extension.

Global Static Rule Limit

In addition to the GUARANTEED_MINIMUM_STATIC_RULES static rules guaranteed for each extension, extensions can enable additional static rulesets depending on the available global static rule limit. This global limit is shared between all extensions and can be used by extensions on a first-come, first-served basis. Extensions shouldn't depend on the global limit having a specific value and should instead use the getAvailableStaticRuleCount API method to find the additional rule limit available to them.

Rules

A single declarative Rule consists of four fields: id, priority, condition, and action. There are the following kinds of rules:

  • Rules that block a network request.
  • Rules that prevent a request from getting blocked by negating any matching blocked rules.
  • Rules that redirect a network request.
  • Rules that modify headers from a network request.

An example rule:

{
"id" : 1,
"priority": 1,
"action" : { "type" : "block" },
"condition" : {
"urlFilter" : "abc",
"domains" : ["foo.com"],
"resourceTypes" : ["script"]
}
}

The above rule will block all script requests originating from "foo.com" to any URL with "abc" as a substring.

The urlFilter field of a rule condition is used to specify the pattern which is matched against the request URL. It is documented on the RuleCondition type below. Some examples of URL filters:

urlFilterMatchesDoes not match
"abc"https://abcd.com
https://example.com/abcd
https://ab.com
"abc*d"https://abcd.com
https://example.com/abcxyzd
https://abc.com
"||a.example.com"https://a.example.com/
https://b.a.example.com/xyz
https://example.com/
"|https*"https://example.comhttp://example.com/
http://https.com
"example*^123|"https://example.com/123
http://abc.com/example?123
https://example.com/1234
https://abc.com/example0123

Dynamic and session-scoped rules

An extension can add or remove rules dynamically using the updateDynamicRules and the updateSessionRules API methods.

  • Rules added using the updateDynamicRules API method are persisted across both sessions and extension updates.
  • Rules added using the updateSessionRules API method are not persisted across Chrome sessions. These rules are backed in memory by Chrome.
  • The number of dynamic and session-scoped rules that an an extension can add is bounded by the MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES constant.

Updating enabled rulesets

An extension can update the set of enabled static rulesets using the updateEnabledRulesets() method.

  • The number of static rulesets which are enabled at one time must not exceed MAX_NUMBER_OF_ENABLED_STATIC_RULESETS.
  • The number of rules across enabled static rulesets across all extensions must not exceed the global limit. Calling getAvailableStaticRuleCount() is recommended to check the number of rules an extension can still enable before the global limit is reached.
  • The set of enabled static rulesets is persisted across sessions but not across extension updates. The "rule_resources" manifest key will determine the set of enabled static rulesets on initial extension install and on each subsequent extension update.

Implementation details

web_accessible_resources

When an extension uses declarativeNetRequest APIs to redirect a public resource request to a resource that is not web accessible, it is blocked and will result in an error. The above holds true even if the resource that is not web accessible is owned by the redirecting extension. To declare resources for use with declarativeNetRequest APIs, populate the "web_accessible_resources" array.

Matching algorithm

Before the request is sent, each extension is queried for an action to take. The following actions are considered at this stage:

  • Actions which block requests of type block
  • Actions which redirect requests of type redirect or upgradeScheme
  • Actions which allow requests of type allow or allowAllRequests

If more than one extension returns an action, the extension whose action type comes first in the list above gets priority. If more than one extension returns an action with the same priority (position in the list), the most recently installed extension gets priority.

When an extension is queried for how to handle a request, the highest priority matching rule is returned. If more than one matching rule has the highest priority, the tie is broken based on the action type, in the following order of decreasing precedence:

  • allow
  • allowAllRequests
  • block
  • upgradeScheme
  • redirect

If the request was not blocked or redirected, the matching modifyHeaders rules are evaluated with the most recently installed extensions getting priority. Within each extension, all modifyHeaders rules with a priority lower than matching allow or allowAllRequests rules are ignored.

If multiple modifyHeaders rules specify the same header, the resulting modification for the header is determined based on the priority of each rule and the operations specified.

  • If a rule has appended to a header, then lower priority rules can only append to that header. set and remove operations are not permitted.
  • If a rule has set a header, then lower priority rules cannot further modify the header, except for append rules from the same extension.
  • If a rule has removed a header, then lower priority rules cannot further modify the header.

Interaction with cached pages

When rules are applied to browsers with pages in the service worker's cached storage, the browser may ignore the set rule for those specific pages until the cached storage is cleared. This is because cached storage is intended to be persistent, and many features like offline use do not expect the cache to be cleared without also clearing a service worker's registration as well. For cases when extensions utilizing declarativeNetRequest must be enabled and disabled repeatedly, the chrome.browsingData API may be used to clear the cache to guarantee proper functionality.

Example

manifest.json:

{
"name": "declarativeNetRequest extension",
"version": "1",
"declarative_net_request": {
"rule_resources": [{
"id": "ruleset_1",
"enabled": true,
"path": "rules.json"
}]
},
"permissions": [
"declarativeNetRequest"
],
"host_permissions": [
"*://*.google.com/*",
"*://*.abcd.com/*",
"*://*.example.com/*",
"https://*.xyz.com/*",
"*://*.headers.com/*",
],
"manifest_version": 3
}

rules.json:

[
{
"id": 1,
"priority": 1,
"action": { "type": "block" },
"condition": {"urlFilter": "google.com", "resourceTypes": ["main_frame"] }
},
{
"id": 2,
"priority": 1,
"action": { "type": "allow" },
"condition": { "urlFilter": "google.com/123", "resourceTypes": ["main_frame"] }
},
{
"id": 3,
"priority": 2,
"action": { "type": "block" },
"condition": { "urlFilter": "google.com/12345", "resourceTypes": ["main_frame"] }
},
{
"id": 4,
"priority": 1,
"action": { "type": "redirect", "redirect": { "url": "https://example.com" } },
"condition": { "urlFilter": "google.com", "resourceTypes": ["main_frame"] }
},
{
"id": 5,
"priority": 1,
"action": { "type": "redirect", "redirect": { "extensionPath": "/a.jpg" } },
"condition": { "urlFilter": "abcd.com", "resourceTypes": ["main_frame"] }
},
{
"id": 6,
"priority": 1,
"action": {
"type": "redirect",
"redirect": {
"transform": { "scheme": "https", "host": "new.example.com" }
}
},
"condition": { "urlFilter": "||example.com", "resourceTypes": ["main_frame"] }
},
{
"id": 7,
"priority": 1,
"action": {
"type": "redirect",
"redirect": {
"regexSubstitution": "https://\\1.xyz.com/"
}
},
"condition": {
"regexFilter": "^https://www\\.(abc|def)\\.xyz\\.com/",
"resourceTypes": [
"main_frame"
]
}
},
{
"id" : 8,
"priority": 2,
"action" : {
"type" : "allowAllRequests"
},
"condition" : {
"urlFilter" : "||b.com/path",
"resourceTypes" : ["sub_frame"]
}
},
{
"id" : 9,
"priority": 1,
"action" : {
"type" : "block"
},
"condition" : {
"urlFilter" : "script.js",
"resourceTypes" : ["script"]
}
},
{
"id": 10,
"priority": 2,
"action": {
"type": "modifyHeaders",
"responseHeaders": [
{ "header": "h1", "operation": "remove" },
{ "header": "h2", "operation": "set", "value": "v2" },
{ "header": "h3", "operation": "append", "value": "v3" }
]
},
"condition": { "urlFilter": "headers.com/123", "resourceTypes": ["main_frame"] }
},
{
"id": 11,
"priority": 1,
"action": {
"type": "modifyHeaders",
"responseHeaders": [
{ "header": "h1", "operation": "set", "value": "v4" },
{ "header": "h2", "operation": "append", "value": "v5" },
{ "header": "h3", "operation": "append", "value": "v6" }
]
},
"condition": { "urlFilter": "headers.com/12345", "resourceTypes": ["main_frame"] }
},
]
  • Consider a navigation to "https://google.com". Rules with id (1) and (4) match. The request will be blocked because blocking rules have higher priority than redirect rules when the "priority" is the same.
  • Consider a navigation to "https://google.com/1234". Rules with id (1), (2), and (4) match. Because the request has a matching allow rule and no higher priority rules, the request is not blocked nor redirected and continues to "https://google.com/1234".
  • Consider a navigation to "https://google.com/12345" Rules with id (1), (2), (3), and (4) match. The request will be blocked because rule (3) has the highest priority, overriding all other matching rules.
  • Consider a navigation to "https://abcd.com". The rule with id (5) matches. Since rule (5) specifies an extension path, the request is redirected to "chrome-extension://EXTENSION_ID/a.jpg".
  • Consider a navigation to "http://example.com/path". The rule with id (6) matches. Since rule (6) specifies a url transform, the request is redirected to "https://new.example.com/path".
  • Consider a navigation to "https://www.abc.xyz.com/path". The rule with id (7) matches. The request will be redirected to "https://abc.xyz.com/path".
  • Consider the following request hierarchy:
    • https://a.com/path (main-frame request)
      • https://b.com/path (sub-frame request, matches rule with id (8))
        • https://c.com/path (sub-frame request, matches rule with id (8))
          • https://c.com/script.js (script request, matches rules with ids (8, 9) but (8) has higher priority)
        • https://b.com/script.js (script request, matches rules with ids (8, 9) but (8) has higher priority)
      • https://d.com/path (sub-frame request)
        • https://d.com/script.js (script request, matches rule with ids (9))All requests in green will be allow-listed due to rule with id (8) and not be evaluated by the extensions' ruleset. Requests in red will be blocked due to rule with id (9).
  • Consider a navigation to "https://headers.com/12345" with response headers { "h1": "initial_1", "h2": "initial_2" }. Rules with id (10) and (11) match. The request will have its response headers modified to { "h2": "v2", "h2": "v5", "h3": "v3", "h3": "v6" }. Header h1 was removed by (10), h2 was set by (10) then appended by (11), and h3 was appended by (10) and (11).

Summary

Types

DomainType

This describes whether the request is first or third party to the frame in which it originated. A request is said to be first party if it has the same domain (eTLD+1) as the frame in which the request originated.

Type

"firstParty"

, or

"thirdParty"

ExtensionActionOptions

Chrome 88+

Properties

  • displayActionCountAsBadgeText

    boolean optional

    Whether to automatically display the action count for a page as the extension's badge text. This preference is persisted across sessions.

  • tabUpdate
    Chrome 89+

    Details of how the tab's action count should be adjusted.

GetDisabledRuleIdsOptions

Chrome 111+

Properties

  • rulesetId

    string

    The id corresponding to a static Ruleset.

GetRulesFilter

Chrome 111+

Properties

  • ruleIds

    number[] optional

    If specified, only rules with matching IDs are included.

HeaderOperation

Chrome 86+

This describes the possible operations for a "modifyHeaders" rule.

Type

"append"

,

"set"

,
or

"remove"

IsRegexSupportedResult

Chrome 87+

Properties

  • isSupported

    boolean

  • reason

    Specifies the reason why the regular expression is not supported. Only provided if isSupported is false.

MatchedRule

Properties

  • ruleId

    number

    A matching rule's ID.

  • rulesetId

    string

    ID of the Ruleset this rule belongs to. For a rule originating from the set of dynamic rules, this will be equal to DYNAMIC_RULESET_ID.

MatchedRuleInfo

Properties

  • tabId

    number

    The tabId of the tab from which the request originated if the tab is still active. Else -1.

  • timeStamp

    number

    The time the rule was matched. Timestamps will correspond to the Javascript convention for times, i.e. number of milliseconds since the epoch.

MatchedRuleInfoDebug

Properties

MatchedRulesFilter

Properties

  • minTimeStamp

    number optional

    If specified, only matches rules after the given timestamp.

  • tabId

    number optional

    If specified, only matches rules for the given tab. Matches rules not associated with any active tab if set to -1.

ModifyHeaderInfo

Chrome 86+

Properties

  • header

    string

    The name of the header to be modified.

  • The operation to be performed on a header.

  • value

    string optional

    The new value for the header. Must be specified for append and set operations.

QueryKeyValue

Properties

  • key

    string

  • replaceOnly

    boolean optional

    Chrome 94+

    If true, the query key is replaced only if it's already present. Otherwise, the key is also added if it's missing. Defaults to false.

  • value

    string

QueryTransform

Properties

  • addOrReplaceParams

    QueryKeyValue[] optional

    The list of query key-value pairs to be added or replaced.

  • removeParams

    string[] optional

    The list of query keys to be removed.

Redirect

Properties

  • extensionPath

    string optional

    Path relative to the extension directory. Should start with '/'.

  • regexSubstitution

    string optional

    Substitution pattern for rules which specify a regexFilter. The first match of regexFilter within the url will be replaced with this pattern. Within regexSubstitution, backslash-escaped digits (\1 to \9) can be used to insert the corresponding capture groups. \0 refers to the entire matching text.

  • transform

    URLTransform optional

    Url transformations to perform.

  • url

    string optional

    The redirect url. Redirects to JavaScript urls are not allowed.

RegexOptions

Chrome 87+

Properties

  • isCaseSensitive

    boolean optional

    Whether the regex specified is case sensitive. Default is true.

  • regex

    string

    The regular expresson to check.

  • requireCapturing

    boolean optional

    Whether the regex specified requires capturing. Capturing is only required for redirect rules which specify a regexSubstition action. The default is false.

RequestDetails

Properties

  • documentId

    string optional

    Chrome 106+

    The unique identifier for the frame's document, if this request is for a frame.

  • documentLifecycle
    Chrome 106+

    The lifecycle of the frame's document, if this request is for a frame.

  • frameId

    number

    The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab.

  • frameType

    FrameType optional

    Chrome 106+

    The type of the frame, if this request is for a frame.

  • initiator

    string optional

    The origin where the request was initiated. This does not change through redirects. If this is an opaque origin, the string 'null' will be used.

  • method

    string

    Standard HTTP method.

  • parentDocumentId

    string optional

    Chrome 106+

    The unique identifier for the frame's parent document, if this request is for a frame and has a parent.

  • parentFrameId

    number

    ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists.

  • requestId

    string

    The ID of the request. Request IDs are unique within a browser session.

  • tabId

    number

    The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab.

  • The resource type of the request.

  • url

    string

    The URL of the request.

RequestMethod

Chrome 91+

This describes the HTTP request method of a network request.

Type

"connect"

,

"delete"

,

"get"

,

"head"

,

"options"

,

"patch"

,

"post"

,

"put"

,
or

"other"

ResourceType

This describes the resource type of the network request.

Type

"main_frame"

,

"sub_frame"

,

"stylesheet"

,

"script"

,

"image"

,

"font"

,

"object"

,

"xmlhttprequest"

,

"ping"

,

"csp_report"

,

"media"

,

"websocket"

,

"webtransport"

,

"webbundle"

,
or

"other"

Rule

Properties

  • The action to take if this rule is matched.

  • condition

    The condition under which this rule is triggered.

  • id

    number

    An id which uniquely identifies a rule. Mandatory and should be >= 1.

  • priority

    number optional

    Rule priority. Defaults to 1. When specified, should be >= 1.

RuleAction

Properties

  • redirect

    Redirect optional

    Describes how the redirect should be performed. Only valid for redirect rules.

  • requestHeaders

    ModifyHeaderInfo[] optional

    Chrome 86+

    The request headers to modify for the request. Only valid if RuleActionType is "modifyHeaders".

  • responseHeaders

    ModifyHeaderInfo[] optional

    Chrome 86+

    The response headers to modify for the request. Only valid if RuleActionType is "modifyHeaders".

  • The type of action to perform.

RuleActionType

Describes the kind of action to take if a given RuleCondition matches.

Type

"block"

,

"redirect"

,

"allow"

,

"upgradeScheme"

,

"modifyHeaders"

,
or

"allowAllRequests"

RuleCondition

Properties

  • domainType

    DomainType optional

    Specifies whether the network request is first-party or third-party to the domain from which it originated. If omitted, all requests are accepted.

  • domains

    string[] optional

    Deprecated since Chrome 101

    Use initiatorDomains instead

    The rule will only match network requests originating from the list of domains.

  • excludedDomains

    string[] optional

    Deprecated since Chrome 101

    Use excludedInitiatorDomains instead

    The rule will not match network requests originating from the list of excludedDomains.

  • excludedInitiatorDomains

    string[] optional

    Chrome 101+

    The rule will not match network requests originating from the list of excludedInitiatorDomains. If the list is empty or omitted, no domains are excluded. This takes precedence over initiatorDomains.

    Notes:

    • Sub-domains like "a.example.com" are also allowed.
    • The entries must consist of only ascii characters.
    • Use punycode encoding for internationalized domains.
    • This matches against the request initiator and not the request url.
    • Sub-domains of the listed domains are also excluded.
  • excludedRequestDomains

    string[] optional

    Chrome 101+

    The rule will not match network requests when the domains matches one from the list of excludedRequestDomains. If the list is empty or omitted, no domains are excluded. This takes precedence over requestDomains.

    Notes:

    • Sub-domains like "a.example.com" are also allowed.
    • The entries must consist of only ascii characters.
    • Use punycode encoding for internationalized domains.
    • Sub-domains of the listed domains are also excluded.
  • excludedRequestMethods

    RequestMethod[] optional

    Chrome 91+

    List of request methods which the rule won't match. Only one of requestMethods and excludedRequestMethods should be specified. If neither of them is specified, all request methods are matched.

  • excludedResourceTypes

    ResourceType[] optional

    List of resource types which the rule won't match. Only one of resourceTypes and excludedResourceTypes should be specified. If neither of them is specified, all resource types except "main_frame" are blocked.

  • excludedTabIds

    number[] optional

    Chrome 92+

    List of tabs.Tab.id which the rule should not match. An ID of tabs.TAB_ID_NONE excludes requests which don't originate from a tab. Only supported for session-scoped rules.

  • initiatorDomains

    string[] optional

    Chrome 101+

    The rule will only match network requests originating from the list of initiatorDomains. If the list is omitted, the rule is applied to requests from all domains. An empty list is not allowed.

    Notes:

    • Sub-domains like "a.example.com" are also allowed.
    • The entries must consist of only ascii characters.
    • Use punycode encoding for internationalized domains.
    • This matches against the request initiator and not the request url.
    • Sub-domains of the listed domains are also matched.
  • isUrlFilterCaseSensitive

    boolean optional

    Whether the urlFilter or regexFilter (whichever is specified) is case sensitive. Default is true.

  • regexFilter

    string optional

    Regular expression to match against the network request url. This follows the RE2 syntax.

    Note: Only one of urlFilter or regexFilter can be specified.

    Note: The regexFilter must be composed of only ASCII characters. This is matched against a url where the host is encoded in the punycode format (in case of internationalized domains) and any other non-ascii characters are url encoded in utf-8.

  • requestDomains

    string[] optional

    Chrome 101+

    The rule will only match network requests when the domain matches one from the list of requestDomains. If the list is omitted, the rule is applied to requests from all domains. An empty list is not allowed.

    Notes:

    • Sub-domains like "a.example.com" are also allowed.
    • The entries must consist of only ascii characters.
    • Use punycode encoding for internationalized domains.
    • Sub-domains of the listed domains are also matched.
  • requestMethods

    RequestMethod[] optional

    Chrome 91+

    List of HTTP request methods which the rule can match. An empty list is not allowed.

    Note: Specifying a requestMethods rule condition will also exclude non-HTTP(s) requests, whereas specifying excludedRequestMethods will not.

  • resourceTypes

    ResourceType[] optional

    List of resource types which the rule can match. An empty list is not allowed.

    Note: this must be specified for allowAllRequests rules and may only include the sub_frame and main_frame resource types.

  • tabIds

    number[] optional

    Chrome 92+

    List of tabs.Tab.id which the rule should match. An ID of tabs.TAB_ID_NONE matches requests which don't originate from a tab. An empty list is not allowed. Only supported for session-scoped rules.

  • urlFilter

    string optional

    The pattern which is matched against the network request url. Supported constructs:

    '*' : Wildcard: Matches any number of characters.

    '|' : Left/right anchor: If used at either end of the pattern, specifies the beginning/end of the url respectively.

    '||' : Domain name anchor: If used at the beginning of the pattern, specifies the start of a (sub-)domain of the URL.

    '^' : Separator character: This matches anything except a letter, a digit or one of the following: _ - . %. This can also match the end of the URL.

    Therefore urlFilter is composed of the following parts: (optional Left/Domain name anchor) + pattern + (optional Right anchor).

    If omitted, all urls are matched. An empty string is not allowed.

    A pattern beginning with ||* is not allowed. Use * instead.

    Note: Only one of urlFilter or regexFilter can be specified.

    Note: The urlFilter must be composed of only ASCII characters. This is matched against a url where the host is encoded in the punycode format (in case of internationalized domains) and any other non-ascii characters are url encoded in utf-8. For example, when the request url is http://abc.рф?q=ф, the urlFilter will be matched against the url http://abc.xn--p1ai/?q=%D1%84.

Ruleset

Properties

  • enabled

    boolean

    Whether the ruleset is enabled by default.

  • id

    string

    A non-empty string uniquely identifying the ruleset. IDs beginning with '_' are reserved for internal use.

  • path

    string

    The path of the JSON ruleset relative to the extension directory.

RulesMatchedDetails

Properties

TabActionCountUpdate

Chrome 89+

Properties

  • increment

    number

    The amount to increment the tab's action count by. Negative values will decrement the count.

  • tabId

    number

    The tab for which to update the action count.

TestMatchOutcomeResult

Chrome 103+

Properties

  • matchedRules

    The rules (if any) that match the hypothetical request.

TestMatchRequestDetails

Chrome 103+

Properties

  • initiator

    string optional

    The initiator URL (if any) for the hypothetical request.

  • method

    RequestMethod optional

    Standard HTTP method of the hypothetical request. Defaults to "get" for HTTP requests and is ignored for non-HTTP requests.

  • tabId

    number optional

    The ID of the tab in which the hypothetical request takes place. Does not need to correspond to a real tab ID. Default is -1, meaning that the request isn't related to a tab.

  • The resource type of the hypothetical request.

  • url

    string

    The URL of the hypothetical request.

UnsupportedRegexReason

Chrome 87+

Describes the reason why a given regular expression isn't supported.

Type

"syntaxError"

, or

"memoryLimitExceeded"

UpdateRuleOptions

Chrome 87+

Properties

  • addRules

    Rule[] optional

    Rules to add.

  • removeRuleIds

    number[] optional

    IDs of the rules to remove. Any invalid IDs will be ignored.

UpdateRulesetOptions

Chrome 87+

Properties

  • disableRulesetIds

    string[] optional

    The set of ids corresponding to a static Ruleset that should be disabled.

  • enableRulesetIds

    string[] optional

    The set of ids corresponding to a static Ruleset that should be enabled.

UpdateStaticRulesOptions

Chrome 111+

Properties

  • disableRuleIds

    number[] optional

    Set of ids corresponding to rules in the Ruleset to disable.

  • enableRuleIds

    number[] optional

    Set of ids corresponding to rules in the Ruleset to enable.

  • rulesetId

    string

    The id corresponding to a static Ruleset.

URLTransform

Properties

  • fragment

    string optional

    The new fragment for the request. Should be either empty, in which case the existing fragment is cleared; or should begin with '#'.

  • host

    string optional

    The new host for the request.

  • password

    string optional

    The new password for the request.

  • path

    string optional

    The new path for the request. If empty, the existing path is cleared.

  • port

    string optional

    The new port for the request. If empty, the existing port is cleared.

  • query

    string optional

    The new query for the request. Should be either empty, in which case the existing query is cleared; or should begin with '?'.

  • queryTransform

    QueryTransform optional

    Add, remove or replace query key-value pairs.

  • scheme

    string optional

    The new scheme for the request. Allowed values are "http", "https", "ftp" and "chrome-extension".

  • username

    string optional

    The new username for the request.

Properties

DYNAMIC_RULESET_ID

Ruleset ID for the dynamic rules added by the extension.

Value

"_dynamic"

GETMATCHEDRULES_QUOTA_INTERVAL

Time interval within which MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL getMatchedRules calls can be made, specified in minutes. Additional calls will fail immediately and set runtime.lastError. Note: getMatchedRules calls associated with a user gesture are exempt from the quota.

Value

10

GUARANTEED_MINIMUM_STATIC_RULES

Chrome 89+

The minimum number of static rules guaranteed to an extension across its enabled static rulesets. Any rules above this limit will count towards the global static rule limit.

Value

30000

MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL

The number of times getMatchedRules can be called within a period of GETMATCHEDRULES_QUOTA_INTERVAL.

Value

20

MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES

Chrome 90+

The maximum number of combined dynamic and session scoped rules an extension can add.

Value

5000

MAX_NUMBER_OF_ENABLED_STATIC_RULESETS

Chrome 94+

The maximum number of static Rulesets an extension can enable at any one time.

Value

10

MAX_NUMBER_OF_REGEX_RULES

The maximum number of regular expression rules that an extension can add. This limit is evaluated separately for the set of dynamic rules and those specified in the rule resources file.

Value

1000

MAX_NUMBER_OF_STATIC_RULESETS

The maximum number of static Rulesets an extension can specify as part of the "rule_resources" manifest key.

Value

50

SESSION_RULESET_ID

Chrome 90+

Ruleset ID for the session-scoped rules added by the extension.

Value

"_session"

Methods

getAvailableStaticRuleCount

chrome.declarativeNetRequest.getAvailableStaticRuleCount(
  callback?: function,
)
Promise Chrome 89+

Returns the number of static rules an extension can enable before the global static rule limit is reached.

Parameters

  • callback

    function optional

    The callback parameter looks like: (count: number) => void

    • count

      number

Returns

  • Promise<number>

    Chrome 91+

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

getDynamicRules

chrome.declarativeNetRequest.getDynamicRules(
  filter?: GetRulesFilter,
  callback?: function,
)
Promise

Returns the current set of dynamic rules for the extension. Callers can optionally filter the list of fetched rules by specifying a filter.

Parameters

  • filter

    GetRulesFilter optional

    Chrome 111+

    An object to filter the list of fetched rules.

  • callback

    function optional

    The callback parameter looks like: (rules: Rule[]) => void

Returns

  • Promise<Rule[]>

    Chrome 91+

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

getEnabledRulesets

chrome.declarativeNetRequest.getEnabledRulesets(
  callback?: function,
)
Promise

Returns the ids for the current set of enabled static rulesets.

Parameters

  • callback

    function optional

    The callback parameter looks like: (rulesetIds: string[]) => void

    • rulesetIds

      string[]

Returns

  • Promise<string[]>

    Chrome 91+

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

getMatchedRules

chrome.declarativeNetRequest.getMatchedRules(
  filter?: MatchedRulesFilter,
  callback?: function,
)
Promise

Returns all rules matched for the extension. Callers can optionally filter the list of matched rules by specifying a filter. This method is only available to extensions with the declarativeNetRequestFeedback permission or having the activeTab permission granted for the tabId specified in filter. Note: Rules not associated with an active document that were matched more than five minutes ago will not be returned.

Parameters

Returns

  • Chrome 91+

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

getSessionRules

chrome.declarativeNetRequest.getSessionRules(
  filter?: GetRulesFilter,
  callback?: function,
)
Promise Chrome 90+

Returns the current set of session scoped rules for the extension. Callers can optionally filter the list of fetched rules by specifying a filter.

Parameters

  • filter

    GetRulesFilter optional

    Chrome 111+

    An object to filter the list of fetched rules.

  • callback

    function optional

    The callback parameter looks like: (rules: Rule[]) => void

Returns

  • Promise<Rule[]>

    Chrome 91+

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

isRegexSupported

chrome.declarativeNetRequest.isRegexSupported(
  regexOptions: RegexOptions,
  callback?: function,
)
Promise Chrome 87+

Checks if the given regular expression will be supported as a regexFilter rule condition.

Parameters

Returns

  • Chrome 91+

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

setExtensionActionOptions

chrome.declarativeNetRequest.setExtensionActionOptions(
  options: ExtensionActionOptions,
  callback?: function,
)
Promise Chrome 88+

Configures if the action count for tabs should be displayed as the extension action's badge text and provides a way for that action count to be incremented.

Parameters

  • callback

    function optional

    Chrome 89+

    The callback parameter looks like: () => void

Returns

  • Promise<void>

    Chrome 91+

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

testMatchOutcome

chrome.declarativeNetRequest.testMatchOutcome(
  request: TestMatchRequestDetails,
  callback?: function,
)
Promise Chrome 103+

Checks if any of the extension's declarativeNetRequest rules would match a hypothetical request. Note: Only available for unpacked extensions as this is only intended to be used during extension development.

Parameters

Returns

  • Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

updateDynamicRules

chrome.declarativeNetRequest.updateDynamicRules(
  options: UpdateRuleOptions,
  callback?: function,
)
Promise

Modifies the current set of dynamic rules for the extension. The rules with IDs listed in options.removeRuleIds are first removed, and then the rules given in options.addRules are added. Notes:

  • This update happens as a single atomic operation: either all specified rules are added and removed, or an error is returned.
  • These rules are persisted across browser sessions and across extension updates.
  • Static rules specified as part of the extension package can not be removed using this function.
  • MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES is the maximum number of combined dynamic and session rules an extension can add.

Parameters

  • Chrome 87+
  • callback

    function optional

    The callback parameter looks like: () => void

Returns

  • Promise<void>

    Chrome 91+

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

updateEnabledRulesets

chrome.declarativeNetRequest.updateEnabledRulesets(
  options: UpdateRulesetOptions,
  callback?: function,
)
Promise

Updates the set of enabled static rulesets for the extension. The rulesets with IDs listed in options.disableRulesetIds are first removed, and then the rulesets listed in options.enableRulesetIds are added. Note that the set of enabled static rulesets is persisted across sessions but not across extension updates, i.e. the rule_resources manifest key will determine the set of enabled static rulesets on each extension update.

Parameters

  • Chrome 87+
  • callback

    function optional

    The callback parameter looks like: () => void

Returns

  • Promise<void>

    Chrome 91+

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

updateSessionRules

chrome.declarativeNetRequest.updateSessionRules(
  options: UpdateRuleOptions,
  callback?: function,
)
Promise Chrome 90+

Modifies the current set of session scoped rules for the extension. The rules with IDs listed in options.removeRuleIds are first removed, and then the rules given in options.addRules are added. Notes:

  • This update happens as a single atomic operation: either all specified rules are added and removed, or an error is returned.
  • These rules are not persisted across sessions and are backed in memory.
  • MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES is the maximum number of combined dynamic and session rules an extension can add.

Parameters

  • callback

    function optional

    The callback parameter looks like: () => void

Returns

  • Promise<void>

    Chrome 91+

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

Events

onRuleMatchedDebug

chrome.declarativeNetRequest.onRuleMatchedDebug.addListener(
  callback: function,
)

Fired when a rule is matched with a request. Only available for unpacked extensions with the declarativeNetRequestFeedback permission as this is intended to be used for debugging purposes only.

Parameters

We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.