This API is still being developed. It is only available to developers building from from source.

chrome.declarativeNetRequest

Description: The chrome.declarativeNetRequest API is used to block or redirect network requests by specifying declarative rules.
Availability: Not fully implemented. You must build Chromium from source to try this API. 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 three 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.

An example rule:

      {
        "id" : 1,
        "action" : { "type" : "block" },
        "condition" : {
          "urlFilter" : "abc",
          "domains" : ["foo.com"],
          "resource_types" : ["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. 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.

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.
[1] An extension wants to block a request, if all the following are true: [2] An extension wants to redirect a request, if all the following are true:

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.
  • Unlike the webRequest API, redirecting requests using the declarativeNetRequest API requires host permissions to both the request URL and the request initiator.
  • 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.
  • Evaluation of declarativeNetRequest rulesets is performed during the onBeforeRequest stage of a network request. Extensions using the webRequest API can intercept requests at different stages of the request.
  • The declarativeNetRequest API only allows extensions to block or redirect requests. 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"] }
        }
      ]
      
  • 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 and instead redirected to "https://example.com".

Summary

Types
ResourceType
Rule
Properties
MAX_NUMBER_OF_ALLOWED_PAGES
MAX_NUMBER_OF_RULES
Methods
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: _ - . %.

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", or "allow" 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 blocked even if there is a blocking rule which matches it.
string (optional) redirectUrl

The redirect url. Only valid if RuleActionType is "redirect".

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.

Methods

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. chrome.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 removed.

function (optional) callback

Called after the page_patterns have been removed. chrome.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