chrome.declarativeNetRequest
- Description
The
chrome.declarativeNetRequestAPI 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
host permissions
Note thatdeclarativeNetRequestFeedbackand host permissions should only be specified when necessary. - AvailabilityChrome 84+
Manifest #
Extensions must declare the "declarativeNetRequest" permission in the extension manifest to use this API. The "declarativeNetRequestFeedback" permission is required to access functions and events which return information on declarative rules matched. Host permissions are required if the extension wants to redirect requests or modify headers. 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",
"*://example.com/*"
],
...
}Rule Resources #
An extension can specify up to MAX_NUMBER_OF_STATIC_RULESETS rulesets as part of the "rule_resources" manifest key. An extension is allowed to enable at least GUARANTEED_MINIMUM_STATIC_RULES static rules. Additional static rule sets may or may not be enabled depending on the available global static rule limit.
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. Some examples of URL filters:
urlFilter | Matches | Does not match |
|---|---|---|
"abc" | https://abcd.com https://example.com/abcd | http://ab.com |
"abc*d" | https://abcd.com https://example.com/abcxyzd | http://abc.com |
"||a.example.com" | https://a.example.com/ https://b.a.example.com/xyz | http://example.com/ |
"|https*" | https://example.com | http://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 API method.
- 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_resourcesmanifest key will determine the set of enabled static rulesets on initial extension install and on each subsequent extension update.
Implementation details #
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
redirectorupgradeScheme - Actions which allow requests of type
alloworallowAllRequests
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:
allowallowAllRequestsblockupgradeSchemeredirect
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.
setandremoveoperations are not permitted. - If a rule has set a header, then lower priority rules cannot further modify the header, except for
appendrules from the same extension. - If a rule has removed a header, then lower priority rules cannot further modify the header.
Comparison with the webRequest API #
- The declarativeNetRequest API allows for evaluating network requests in the browser itself. This makes it more performant than the webRequest API, where each network request is evaluated in JavaScript in the extension process.
- Because the requests are not intercepted by the extension process, declarativeNetRequest removes the need for extensions to have a background page; resulting in less memory consumption.
- Unlike the webRequest API, blocking requests using the declarativeNetRequest API requires no host permissions.
- The declarativeNetRequest API provides better privacy to users because extensions can't actually read the network requests made on the user's behalf.
- Unlike the webRequest API, any images or iframes blocked using the declarativeNetRequest API are automatically collapsed in the DOM.
- While deciding whether a request is to be blocked or redirected, the declarativeNetRequest API is given priority over the webRequest API because it allows for synchronous interception. Similarly, any headers removed through declarativeNetRequest API are not made visible to web request extensions.
- The webRequest API is more flexible as compared to the declarativeNetRequest API because it allows extensions to evaluate a request programmatically.
Example #
manifest.json
{
"name": "declarativeNetRequest extension",
"version": "1",
"declarative_net_request": {
"rule_resources": [{
"id": "ruleset_1",
"enabled": true,
"path": "rules.json"
}]
},
"permissions": [
"*://*.google.com/*",
"*://*.abcd.com/*",
"*://*.example.com/*",
"http://*.xyz.com/*",
"*://*.headers.com/*",
"declarativeNetRequest"
],
"manifest_version": 2
}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": "^http://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
"http://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
"http://google.com/1234". Rules with id (1), (2), and (4) match. Because the request has a matchingallowrule and no higher priority rules, the request is not blocked nor redirected and continues to"http://google.com/1234". - Consider a navigation to
"http://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
"http://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
"http://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://c.com/path (sub-frame request, matches rule with id (8))
- 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).
- https://b.com/path (sub-frame request, matches rule with id (8))
- https://a.com/path (main-frame request)
- Consider a navigation to
"http://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" }. Headerh1was removed by (10),h2was set by (10) then appended by (11), andh3was appended by (10) and (11).
Summary
- Types
- Properties
- Methods
getAvailableStaticRuleCount(): Promise<object>getAvailableStaticRuleCount(callback: function): voidgetDynamicRules(): Promise<object>getDynamicRules(callback: function): voidgetEnabledRulesets(): Promise<object>getEnabledRulesets(callback: function): voidgetMatchedRules(filter?: MatchedRulesFilter): Promise<object>getMatchedRules(filter?: MatchedRulesFilter, callback: function): voidgetSessionRules(): Promise<object>getSessionRules(callback: function): voidisRegexSupported(regexOptions: RegexOptions): Promise<object>isRegexSupported(regexOptions: RegexOptions, callback: function): voidsetExtensionActionOptions(options: ExtensionActionOptions): Promise<object>setExtensionActionOptions(options: ExtensionActionOptions, callback?: function): voidupdateDynamicRules(options: UpdateRuleOptions): Promise<object>updateDynamicRules(options: UpdateRuleOptions, callback?: function): voidupdateEnabledRulesets(options: UpdateRulesetOptions): Promise<object>updateEnabledRulesets(options: UpdateRulesetOptions, callback?: function): voidupdateSessionRules(options: UpdateRuleOptions): Promise<object>updateSessionRules(options: UpdateRuleOptions, callback?: function): void - Events
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.
Enum
"firstParty", or "thirdParty"
ExtensionActionOptions
Properties
- displayActionCountAsBadgeTextboolean optional
Whether to automatically display the action count for a page as the extension's badge text. This preference is persisted across sessions.
- tabUpdateTabActionCountUpdate optionalChrome 89+
Details of how the tab's action count should be adjusted.
HeaderOperation
This describes the possible operations for a "modifyHeaders" rule.
Enum
"append", "set", or "remove"
IsRegexSupportedResult
Properties
- isSupportedboolean
- reasonUnsupportedRegexReason optional
Specifies the reason why the regular expression is not supported. Only provided if
isSupportedis false.
MatchedRule
Properties
- ruleIdnumber
A matching rule's ID.
- rulesetIdstring
ID of the
Rulesetthis rule belongs to. For a rule originating from the set of dynamic rules, this will be equal toDYNAMIC_RULESET_ID.
MatchedRuleInfo
Properties
- rule
- tabIdnumber
The tabId of the tab from which the request originated if the tab is still active. Else -1.
- timeStampnumber
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
- request
Details about the request for which the rule was matched.
- rule
MatchedRulesFilter
Properties
- minTimeStampnumber optional
If specified, only matches rules after the given timestamp.
- tabIdnumber optional
If specified, only matches rules for the given tab. Matches rules not associated with any active tab if set to -1.
ModifyHeaderInfo
Properties
- headerstring
The name of the header to be modified.
- operation
The operation to be performed on a header.
- valuestring optional
The new value for the header. Must be specified for
appendandsetoperations.
QueryKeyValue
Properties
- keystring
- valuestring
QueryTransform
Properties
- addOrReplaceParamsQueryKeyValue[] optional
The list of query key-value pairs to be added or replaced.
- removeParamsstring[] optional
The list of query keys to be removed.
Redirect
Properties
- extensionPathstring optional
Path relative to the extension directory. Should start with '/'.
- regexSubstitutionstring optional
Substitution pattern for rules which specify a
regexFilter. The first match ofregexFilterwithin the url will be replaced with this pattern. WithinregexSubstitution, backslash-escaped digits (\1 to \9) can be used to insert the corresponding capture groups. \0 refers to the entire matching text. - transformURLTransform optional
Url transformations to perform.
- urlstring optional
The redirect url. Redirects to JavaScript urls are not allowed.
RegexOptions
Properties
- isCaseSensitiveboolean optional
Whether the
regexspecified is case sensitive. Default is true. - regexstring
The regular expresson to check.
- requireCapturingboolean optional
Whether the
regexspecified requires capturing. Capturing is only required for redirect rules which specify aregexSubstitionaction. The default is false.
RequestDetails
Properties
- frameIdnumber
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 (
typeismain_frameorsub_frame),frameIdindicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. - initiatorstring 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.
- methodstring
Standard HTTP method.
- parentFrameIdnumber
ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists.
- requestIdstring
The ID of the request. Request IDs are unique within a browser session.
- tabIdnumber
The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab.
- type
The resource type of the request.
- urlstring
The URL of the request.
RequestMethod
This describes the HTTP request method of a network request.
Enum
"delete", "get", "head", "options", "patch", "post", or "put"
ResourceType
This describes the resource type of the network request.
Enum
"main_frame", "sub_frame", "stylesheet", "script", "image", "font", "object", "xmlhttprequest", "ping", "csp_report", "media", "websocket", or "other"
Rule
Properties
- action
The action to take if this rule is matched.
- condition
The condition under which this rule is triggered.
- idnumber
An id which uniquely identifies a rule. Mandatory and should be >= 1.
- prioritynumber optional
Rule priority. Defaults to 1. When specified, should be >= 1.
RuleAction
Properties
- redirectRedirect optional
Describes how the redirect should be performed. Only valid for redirect rules.
- requestHeadersModifyHeaderInfo[] optionalChrome 86+
The request headers to modify for the request. Only valid if RuleActionType is "modifyHeaders".
- responseHeadersModifyHeaderInfo[] optionalChrome 86+
The response headers to modify for the request. Only valid if RuleActionType is "modifyHeaders".
- type
The type of action to perform.
RuleActionType
Describes the kind of action to take if a given RuleCondition matches.
Enum
"block", "redirect", "allow", "upgradeScheme", "modifyHeaders", or "allowAllRequests"
RuleCondition
Properties
- domainsstring[] optional
The rule will only match network requests originating from the list of
domains. 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.
- domainTypeDomainType 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.
- excludedDomainsstring[] optional
The rule will not match network requests originating from the list of
excludedDomains. If the list is empty or omitted, no domains are excluded. This takes precedence overdomains.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.
- excludedRequestMethodsRequestMethod[] optionalUnknown version
List of request methods which the rule won't match. Only one of
requestMethodsandexcludedRequestMethodsshould be specified. If neither of them is specified, all request methods are matched. - excludedResourceTypesResourceType[] optional
List of resource types which the rule won't match. Only one of
resourceTypesandexcludedResourceTypesshould be specified. If neither of them is specified, all resource types except "main_frame" are blocked. - excludedTabIdsnumber[] optionalUnknown version
List of
tabs.Tab.idwhich the rule should not match. An ID oftabs.TAB_ID_NONEexcludes requests which don't originate from a tab. Only supported for session-scoped rules. - isUrlFilterCaseSensitiveboolean optional
Whether the
urlFilterorregexFilter(whichever is specified) is case sensitive. Default is true. - regexFilterstring optional
Regular expression to match against the network request url. This follows the RE2 syntax.
Note: Only one of
urlFilterorregexFiltercan be specified.Note: The
regexFiltermust 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. - requestMethodsRequestMethod[] optionalUnknown version
List of HTTP request methods which the rule can match. An empty list is not allowed. Note: Non HTTP requests are considered to have the "get" request method.
- resourceTypesResourceType[] optional
List of resource types which the rule can match. An empty list is not allowed.
Note: this must be specified for
allowAllRequestsrules and may only include thesub_frameandmain_frameresource types. - tabIdsnumber[] optionalUnknown version
List of
tabs.Tab.idwhich the rule should match. An ID oftabs.TAB_ID_NONEmatches requests which don't originate from a tab. An empty list is not allowed. Only supported for session-scoped rules. - urlFilterstring 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
urlFilteris 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
urlFilterorregexFiltercan be specified.Note: The
urlFiltermust 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=ф, theurlFilterwill be matched against the url http://abc.xn--p1ai/?q=%D1%84.
Ruleset
Properties
- enabledboolean
Whether the ruleset is enabled by default.
- idstring
A non-empty string uniquely identifying the ruleset. IDs beginning with '_' are reserved for internal use.
- pathstring
The path of the JSON ruleset relative to the extension directory.
RulesMatchedDetails
Properties
- rulesMatchedInfo
Rules matching the given filter.
TabActionCountUpdate
Properties
- incrementnumber
The amount to increment the tab's action count by. Negative values will decrement the count.
- tabIdnumber
The tab for which to update the action count.
UnsupportedRegexReason
Describes the reason why a given regular expression isn't supported.
Enum
"syntaxError", or "memoryLimitExceeded"
UpdateRuleOptions
Properties
- addRulesRule[] optional
Rules to add.
- removeRuleIdsnumber[] optional
IDs of the rules to remove. Any invalid IDs will be ignored.
UpdateRulesetOptions
Properties
URLTransform
Properties
- fragmentstring optional
The new fragment for the request. Should be either empty, in which case the existing fragment is cleared; or should begin with '#'.
- hoststring optional
The new host for the request.
- passwordstring optional
The new password for the request.
- pathstring optional
The new path for the request. If empty, the existing path is cleared.
- portstring optional
The new port for the request. If empty, the existing port is cleared.
- querystring optional
The new query for the request. Should be either empty, in which case the existing query is cleared; or should begin with '?'.
- queryTransformQueryTransform optional
Add, remove or replace query key-value pairs.
- schemestring optional
The new scheme for the request. Allowed values are "http", "https", "ftp" and "chrome-extension".
- usernamestring optional
The new username for the request.
Properties
DYNAMIC_RULESET_ID
Ruleset ID for the dynamic rules added by the extension.
Value
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
GUARANTEED_MINIMUM_STATIC_RULES
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 rule limit.
Value
MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL
The number of times getMatchedRules can be called within a period of GETMATCHEDRULES_QUOTA_INTERVAL.
Value
MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES
The maximum number of combined dynamic and session scoped rules an extension can add.
Value
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
MAX_NUMBER_OF_STATIC_RULESETS
The maximum number of static Rulesets an extension can specify as part of the "rule_resources" manifest key.
Value
SESSION_RULESET_ID
Ruleset ID for the session-scoped rules added by the extension.
Value
Methods
getAvailableStaticRuleCount
getAvailableStaticRuleCount(): Promise<object>getAvailableStaticRuleCount(callback: function): voidReturns the number of static rules an extension can enable before the global static rule limit is reached.
Result
- return/callbackasync
The
getAvailableStaticRuleCountmethod provides its result via callback or returned as aPromise(MV3 only).- countnumber
getDynamicRules
getDynamicRules(): Promise<object>getDynamicRules(callback: function): voidReturns the current set of dynamic rules for the extension.
Result
- return/callbackasync
Called with the set of dynamic rules. An error might be raised in case of transient internal errors.
The
getDynamicRulesmethod provides its result via callback or returned as aPromise(MV3 only).- rulesRule[]
getEnabledRulesets
getEnabledRulesets(): Promise<object>getEnabledRulesets(callback: function): voidReturns the ids for the current set of enabled static rulesets.
Result
- return/callbackasync
Called with a list of ids, where each id corresponds to an enabled static
Ruleset.The
getEnabledRulesetsmethod provides its result via callback or returned as aPromise(MV3 only).- rulesetIdsstring[]
getMatchedRules
getMatchedRules(filter?: MatchedRulesFilter): Promise<object>getMatchedRules(filter?: MatchedRulesFilter, callback: function): voidReturns 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
- filterMatchedRulesFilter optional
An object to filter the list of matched rules.
Result
- return/callbackasync
Called once the list of matched rules has been fetched. In case of an error,
runtime.lastErrorwill be set and no rules will be returned. This can happen for multiple reasons, such as insufficient permissions, or exceeding the quota.The
getMatchedRulesmethod provides its result via callback or returned as aPromise(MV3 only).- details
getSessionRules
getSessionRules(): Promise<object>getSessionRules(callback: function): voidReturns the current set of session scoped rules for the extension.
Result
- return/callbackasync
Called with the set of session scoped rules.
The
getSessionRulesmethod provides its result via callback or returned as aPromise(MV3 only).- rulesRule[]
isRegexSupported
isRegexSupported(regexOptions: RegexOptions): Promise<object>isRegexSupported(regexOptions: RegexOptions, callback: function): voidChecks if the given regular expression will be supported as a regexFilter rule condition.
Parameters
- regexOptions
The regular expression to check.
Result
- return/callbackasync
Called with details consisting of whether the regular expression is supported and the reason if not.
The
isRegexSupportedmethod provides its result via callback or returned as aPromise(MV3 only).- result
setExtensionActionOptions
setExtensionActionOptions(options: ExtensionActionOptions): Promise<object>setExtensionActionOptions(options: ExtensionActionOptions, callback?: function): voidConfigures 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
- options
Result
- return/callbackasyncChrome 89+
The
setExtensionActionOptionsmethod provides its result via callback or returned as aPromise(MV3 only). It has no parameters.
updateDynamicRules
updateDynamicRules(options: UpdateRuleOptions): Promise<object>updateDynamicRules(options: UpdateRuleOptions, callback?: function): voidModifies 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_RULESis the maximum number of combined dynamic and session rules an extension can add.
Parameters
- optionsChrome 87+
Result
- return/callbackasync
Called once the update is complete or has failed. In case of an error,
runtime.lastErrorwill be set and no change will be made to the rule set. This can happen for multiple reasons, such as invalid rule format, duplicate rule ID, rule count limit exceeded, internal errors, and others.The
updateDynamicRulesmethod provides its result via callback or returned as aPromise(MV3 only). It has no parameters.
updateEnabledRulesets
updateEnabledRulesets(options: UpdateRulesetOptions): Promise<object>updateEnabledRulesets(options: UpdateRulesetOptions, callback?: function): voidUpdates 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
- optionsChrome 87+
Result
- return/callbackasync
Called once the update is complete. In case of an error,
runtime.lastErrorwill be set and no change will be made to set of enabled rulesets. This can happen for multiple reasons, such as invalid ruleset IDs, rule count limit exceeded, or internal errors.The
updateEnabledRulesetsmethod provides its result via callback or returned as aPromise(MV3 only). It has no parameters.
updateSessionRules
updateSessionRules(options: UpdateRuleOptions): Promise<object>updateSessionRules(options: UpdateRuleOptions, callback?: function): voidModifies 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_RULESis the maximum number of combined dynamic and session rules an extension can add.
Parameters
- options
Result
- return/callbackasync
Called once the update is complete or has failed. In case of an error,
runtime.lastErrorwill be set and no change will be made to the rule set. This can happen for multiple reasons, such as invalid rule format, duplicate rule ID, rule count limit exceeded, and others.The
updateSessionRulesmethod provides its result via callback or returned as aPromise(MV3 only). It has no parameters.
Events
onRuleMatchedDebug
onRuleMatchedDebug.addListener(listener: 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.
Event
- listenerfunction
The listener parameter should be a function that looks like this:
(info: MatchedRuleInfoDebug) => {...}- Chrome 85+
The rule that has been matched along with information about the associated request.