This API is in beta. It is only available to Chrome users on the beta channel and dev channel.

chrome.declarativeNetRequest

Description: The chrome.declarativeNetRequest API is used to block or modify network requests by specifying declarative rules.
Availability: Beta and Dev channels only. Learn more.
Permissions: "declarativeNetRequest"
host permissions

Manifest

You must declare the "declarativeNetRequest" permission in the extension manifest to use this API. Host permissions are required if the extension wants to redirect requests. You 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 a single element, the path to a JSON file containing the declarative rules to use, as shown below.

      {
        "name": "My extension",
        ...
      
        "declarative_net_request" : {
          "rule_resources" : ["rules.json"]
        },
        "permissions": [
          "declarativeNetRequest",
          "*://example.com/*"
        ],
        ...
      }
      

Rule Resources

The JSON file specified as part of "rule_resources" in the manifest contains a list of rules. The number of rules that an extension can specify is bound by the chrome.declarativeNetRequest.MAX_NUMBER_OF_RULES constant.

Rules

A single declarative rule consists of four fields: id, priority, condition and action. See the Rule section below for more information on the format. 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 remove headers from a network request.

An example rule:

      {
        "id" : 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

Page allowlisting

To disable the extension ruleset on a particular page, extensions can use the chrome.declarativeNetRequest.addAllowedPages API method. This allows extensions to specify match patterns that are compared against the tab URL. Any requests originating from these pages are not evaluated against the extension ruleset. The number of such patterns an extension can add is bound by the chrome.declarativeNetRequest.MAX_NUMBER_OF_ALLOWED_PAGES constant.

Dynamic rules

To add rules dynamically, extensions can use the chrome.declarativeNetRequest.addDynamicRules API method.

  • The number of dynamic rules that an an extension can add is bounded by the chrome.declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_RULES constant.
  • An extension's dynamic ruleset is maintained separately from its static ruleset (the ruleset specified as part of the extension package). For example, it's possible to have the same rule ID across static and dynamic rulesets.
  • For conflicting actions, dynamic rules are given priority over static rules.

Implementation details

Matching algorithm

  • If any extension ruleset wants to block a request[1], the network request is blocked.
  • If the request is not blocked, the request is redirected if any extension ruleset wants to redirect the request[2]. The most recently installed extension gets preference here. If multiple redirect rules from an extension’s ruleset match, the rule with the greatest priority determines the redirect URL.
  • If the request is not blocked or redirected, removeHeaders rules are evaluated[3]. Rules from all extensions are evaluated to determine the set of removed headers.
[1] An extension wants to block a request, if all the following are true:
  • The extension has a matching block rule. Note the priority order between the different block/allow actions:
    dynamic allow > dynamic block > static allow > static block.
  • The page from which the request originated is not allow-listed by the extension using chrome.declarativeNetRequest.addAllowedPages.
[2] An extension wants to redirect a request, if all the following are true:
  • The extension has a matching redirect rule. Note the priority order between the different redirect/allow actions:
    dynamic allow > dynamic redirect > static allow > static redirect.
  • The page from which the request originated is not allow-listed by the extension using chrome.declarativeNetRequest.addAllowedPages.
[3] An extension wants to remove a header from a request, if all the following are true:
  • The extension has a matching removeHeaders rule. Note the priority order between the different removeHeaders/allow actions:
    dynamic allow > dynamic removeHeaders > static allow > static removeHeaders.
  • The page from which the request originated is not allow-listed by the extension using chrome.declarativeNetRequest.addAllowedPages.

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 or removing headers 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" : ["rules.json"]
        },
        "permissions" : ["*://google.com/*", "declarativeNetRequest"],
        "manifest_version" : 2
      }
      

rules.json

      [
        {
          "id" : 1,
          "action": { "type" : "block" },
          "condition" : {"urlFilter" : "google.com", "resourceTypes" : ["main_frame"] }
        },
        {
          "id" : 2,
          "action" : { "type" : "allow" },
          "condition" : { "urlFilter" : "google.com/123", "resourceTypes" : ["main_frame"] }
        },
        {
          "id" : 3,
          "priority" : 1,
          "action" : { "type" : "redirect", "redirectUrl" : "https://example.com" },
          "condition" : { "urlFilter" : "google.com", "resourceTypes" : ["main_frame"] }
        },
        {
          "id" : 4,
          "priority" : 1,
          "action" : { "type" : "redirect", "redirectUrl" : "/a.jpg" },
          "condition" : { "urlFilter" : "abcd.com", "resourceTypes" : ["main_frame"] }
        }
      ]
      
  • Consider a navigation to "http://google.com". Rules with id (1) and (3) match. The request will be blocked because blocking rules have higher priority than redirect rules.
  • Consider a navigation to "http://google.com/1234". Rules with id (1), (2), and (3) match. Because the request has a matching allow rule, the request is not blocked nor redirected and continues to "http://google.com/1234".
  • Consider a navigation to "http://abcd.com". The rule with id (4) matches. Since rule (4) specifies a relative URL, the request is redirected to "chrome-extension://<extension-id>/a.jpg".

Summary

Types
ResourceType
Rule
Properties
MAX_NUMBER_OF_ALLOWED_PAGES
MAX_NUMBER_OF_RULES
MAX_NUMBER_OF_DYNAMIC_RULES
Methods
addDynamicRules chrome.declarativeNetRequest.addDynamicRules(array of Rule rules, function callback)
removeDynamicRules chrome.declarativeNetRequest.removeDynamicRules(array of integer rule_ids, function callback)
getDynamicRules chrome.declarativeNetRequest.getDynamicRules(function callback)
addAllowedPages chrome.declarativeNetRequest.addAllowedPages(array of string page_patterns, function callback)
removeAllowedPages chrome.declarativeNetRequest.removeAllowedPages(array of string page_patterns, function callback)
getAllowedPages chrome.declarativeNetRequest.getAllowedPages(function callback)

Types

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
integer id

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

integer (optional) priority

Rule priority. Mandatory for redirect rules and should be >= 1. This is used to break ties between multiple matching redirect rules.

object condition

The condition under which this rule is triggered.

string (optional) urlFilter

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.

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.

boolean (optional) isUrlFilterCaseSensitive

Whether the urlFilter is case sensitive. Default is true.

array of string (optional) domains

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.

Note: sub-domains like "a.example.com" are also allowed. The entries must consist of only ascii characters. Use punycode encoding for internationalized domains.

array of string (optional) excludedDomains

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 over domains.

Note: sub-domains like "a.example.com" are also allowed. The entries must consist of only ascii characters. Use punycode encoding for internationalized domains.

array of ResourceType (optional) resourceTypes

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

array of ResourceType (optional) excludedResourceTypes

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.

enum of "firstParty", or "thirdParty" (optional) domainType

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

firstParty
The network request is first party to the frame in which it originated.
thirdParty
The network request is third party to the frame in which it originated.
object action

The action to take if this rule is matched.

enum of "block", "redirect", "allow", or "removeHeaders" type

The type of action to perform.

block
Block the network request.
redirect
Redirect the network request.
allow
Allow the network request. The request won't be intercepted if there is an allow rule which matches it.
removeHeaders
Remove request/response headers from the network request.
string (optional) redirectUrl

The redirect url. Only valid if RuleActionType is "redirect". Can be specified as an absolute url or a relative url (starting with '/'), which is relative to the extension which specified the rule.

array of enum of "cookie", "referer", or "setCookie" (optional) removeHeadersList

The headers to remove from the request. Only valid if RuleActionType is "removeHeaders".

Properties

100 chrome.declarativeNetRequest.MAX_NUMBER_OF_ALLOWED_PAGES The maximum number of allowed pages that an extension can add.
30,000 chrome.declarativeNetRequest.MAX_NUMBER_OF_RULES The maximum number of rules that an extension can specify in the rule resources file. Any excess rules will be ignored and an install warning will be raised.
5,000 chrome.declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_RULES The maximum number of dynamic rules that an extension can add.

Methods

addDynamicRules

chrome.declarativeNetRequest.addDynamicRules(array of Rule rules, function callback)

Beta and Dev channels only. Learn more.

Adds rules to the current set of dynamic rules for the extension. These rules are persisted across browser sessions. Note: MAX_NUMBER_OF_DYNAMIC_RULES is the maximum number of dynamic rules an extension can add.

Parameters
array of Rule rules

Since Chrome 76. Warning: this is the current Beta channel. Learn more.

The rules to add.

function (optional) callback

Called once the given rules are added. In case of an error, runtime.lastError will be set to denote the error message and no rules will be added. This can happen for multiple reasons, such as invalid rule format, duplicate rule ID, rule count limit exceeded, internal errors, and others.

If you specify the callback parameter, it should be a function that looks like this:

function() {...};

removeDynamicRules

chrome.declarativeNetRequest.removeDynamicRules(array of integer rule_ids, function callback)

Beta and Dev channels only. Learn more.

Removes rules corresponding to rule_ids from the current set of dynamic rules for the extension. Any rule_ids not already present are ignored. Note that static rules specified as part of the extension package can not be removed using this function.

Parameters
array of integer rule_ids

Since Chrome 76. Warning: this is the current Beta channel. Learn more.

The IDs of dynamic rules to remove.

function (optional) callback

Called once the rules are removed. In case of an error, runtime.lastError will be set to denote the error message and no rules will be removed. This may happen due to internal errors.

If you specify the callback parameter, it should be a function that looks like this:

function() {...};

getDynamicRules

chrome.declarativeNetRequest.getDynamicRules(function callback)

Beta and Dev channels only. Learn more.

Returns the current set of dynamic rules for the extension.

Parameters
function callback

Called with the set of dynamic rules. An error might be raised in case of transient internal errors.

The callback parameter should be a function that looks like this:

function(array of Rule rules) {...};
array of Rule rules

addAllowedPages

chrome.declarativeNetRequest.addAllowedPages(array of string page_patterns, function callback)

Adds page_patterns to the set of allowed pages. Requests from these pages are not intercepted by the extension. These are persisted across browser sessions. Note: MAX_NUMBER_OF_ALLOWED_PAGES is the maximum number of allowed page an extension can add. Also, adding page patterns is atomic. In case of an error, no page pattern is added.

Parameters
array of string page_patterns

Array of match patterns which are to be allowed.

function (optional) callback

Called after the page_patterns have been added. runtime.lastError will be set in case of an error, for example if an invalid page pattern is specified or the extension exceeded the maximum page patterns limit.

If you specify the callback parameter, it should be a function that looks like this:

function() {...};

removeAllowedPages

chrome.declarativeNetRequest.removeAllowedPages(array of string page_patterns, function callback)

Removes page_patterns from the set of allowed pages. Note: Removing page patterns is atomic. In case of an error, no page pattern is removed.

Parameters
array of string page_patterns

Array of match patterns which are to be removed.

function (optional) callback

Called after the page_patterns have been removed. runtime.lastError will be set in case of an error.

If you specify the callback parameter, it should be a function that looks like this:

function() {...};

getAllowedPages

chrome.declarativeNetRequest.getAllowedPages(function callback)

Returns the current set of allowed pages.

Parameters
function callback

Called with the set of currently allowed pages.

The callback parameter should be a function that looks like this:

function(array of string result) {...};
array of string result