Google Chrome Extensions

chrome.declarativeWebRequest

Warning: This API is still under development. It is only available for Chrome users on the dev early release channel and beta release channel.

Notes

Use the chrome.declarativeWebRequest module to intercept, block, or modify requests in-flight. It is significantly faster than the chrome.webRequest API because you can register rules that are evaluated in the browser rather than the JavaScript engine which reduces roundtrip latencies and allows for very high efficiency.

Manifest

You must declare the "declarativeWebRequest" permission in the extension manifest to use this API, along with host permissions for any hosts whose network requests you want to access.

{
  "name": "My extension",
  ...
  "permissions": [
    "declarativeWebRequest",
    "*://*.google.com"
  ],
  ...
}

Rules

The Declarative Web Request API follows the concepts of the Declarative API. You can register rules to the chrome.declarativeWebRequest.onRequest event object.

The Declarative Web Request API supports a single type of match criteria, the RequestMatcher. The RequestMatcher matches network requests if and only if all listed criteria are met. The following RequestMatcher would match a network request when the user enters "http://www.example.com" in the URL bar:

var matcher = new chrome.declarativeWebRequest.RequestMatcher({
  url: { hostSuffix: 'example.com', schemes: ['http'] },
  resourceType: ['main_frame']
  });

Requests to "https://www.example.com" would be rejected by the RequestMatcher due to the scheme. Also all requests for an embedded iframe would be rejected due to the resourceType.

Note: All conditions and actions are created via a constructor as shown in the example above.

In order to cancel all requests to "example.com", you can define a rule as follows:

var rule = {
  conditions: [
    new chrome.declarativeWebRequest.RequestMatcher({
      url: { hostSuffix: 'example.com' } })
  ],
  actions: [
    new chrome.declarativeWebRequest.CancelRequest()
  ]};

In order to cancel all requests to "example.com" and "foobar.com", you can add a second condition, as each condition is sufficient to trigger all specified actions:

var rule2 = {
  conditions: [
    new chrome.declarativeWebRequest.RequestMatcher({
      url: { hostSuffix: 'example.com' } }),
    new chrome.declarativeWebRequest.RequestMatcher({
      url: { hostSuffix: 'foobar.com' } })
  ],
  actions: [
    new chrome.declarativeWebRequest.CancelRequest()
  ]};

Register rules as follows:

chrome.declarativeWebRequest.onRequest.addRules([rule2]);

Note: You should always register or unregister rules in bulk rather than individually because each of these operations recreates internal data structures. This re-creation is computationally expensive but facilitates a very fast URL matching algorithm for hundreds of thousands of URLs.

Evaluation of conditions and actions

The Declarative Web Request API follows the Life cycle model for web requests of the Web Request API. This means that conditions can only be tested at specific stages of a web request and, likewise, actions can also only be executed at specific stages. The following tables list the request stages that are compatible with conditions and actions.

Request stages during which condition attributes can be processed.
Condition attribute onBeforeRequest onBeforeSendHeaders onHeadersReceived onAuthRequired
url
resourceType
contentType
excludeContentType
responseHeaders
excludeResponseHeaders
Request stages during which actions can be executed.
Event onBeforeRequest onBeforeSendHeaders onHeadersReceived onAuthRequired
AddRequestCookie
AddResponseCookie
AddResponseHeader
CancelRequest
EditRequestCookie
EditResponseCookie
IgnoreRules
RedirectByRegEx
RedirectRequest
RedirectToEmptyDocument
RedirectToTransparentImage
RemoveRequestCookie
RemoveRequestHeader
RemoveResponseCookie
RemoveResponseHeader
SetRequestHeader

Example: It is possible to combine a new chrome.declarativeWebRequest.RequestMatcher({contentType: ["image/jpeg"]}) condition with a new chrome.declarativeWebRequest.CancelRequest() action because both of them can be evaluated in the onHeadersReceived stage. It is, however, impossible to combine the request matcher with a new chrome.declarativeWebRequest.RedirectToTransparentImage() because redirects cannot be executed any more by the time the content type has been determined.

Using priorities to override rules

Rules can be associated with priorities as described in the Events API. This mechanism can be used to express exceptions. The following example will block all requests to images named "evil.jpg" except on the server "myserver.com".

var rule1 = {
  priority: 100,
  conditions: [
    new chrome.declarativeWebRequest.RequestMatcher({
        url: { pathEquals: 'evil.jpg' } })
  ],
  actions: [
    new chrome.declarativeWebRequest.CancelRequest()
  ]
};
var rule2 = {
  priority: 1000,
  conditions: [
    new chrome.declarativeWebRequest.RequestMatcher({
      url: { hostSuffix: '.myserver.com' } })
  ],
  actions: [
    new chrome.declarativeWebRequest.IgnoreRules({
      lowerPriorityThan: 1000 })
  ]
};
chrome.declarativeWebRequest.onRequest.addRules([rule1, rule2]);

It is important to recognize that the IgnoreRules action is not persisted across request stages. All conditions of all rules are evaluated at each stage of a web request. If an IgnoreRules action is executed, it applies only to other actions that are executed for the same web request in the same stage.

API Reference: chrome.declarativeWebRequest

Types

HeaderFilter

( object )
Filters request headers for various criteria.

Properties of HeaderFilter

namePrefix ( optional string )
Matches if the header name starts with the specified string.
nameSuffix ( optional string )
Matches if the header name ends with the specified string.
nameContains ( optional array of string or string )
Matches if the header name contains all of the specified strings.
nameEquals ( optional string )
Matches if the header name is equal to the specified string.
valuePrefix ( optional string )
Matches if the header value starts with the specified string.
valueSuffix ( optional string )
Matches if the header value ends with the specified string.
valueContains ( optional array of string or string )
Matches if the header value contains all of the specified strings.
valueEquals ( optional string )
Matches if the header value is equal to the specified string.

RequestMatcher

( object )
Matches network events by various criteria.

Properties of RequestMatcher

url ( optional events.UrlFilter )
Matches if the condition of the UrlFilter are fulfilled for the URL of the request.
resourceType ( optional array of enumerated string ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"] )
Matches if the request type of a request is contained in the list. Requests that cannot match any of the types will be filtered out.
contentType ( optional array of string )
Matches if the MIME media type of a response (from the HTTP Content-Type header) is contained in the list.
excludeContentType ( optional array of string )
Matches if the MIME media type of a response (from the HTTP Content-Type header) is not contained in the list.
responseHeaders ( optional array of HeaderFilter )
Matches if some of the response headers is matched by one of the HeaderFilters.
excludeResponseHeaders ( optional array of HeaderFilter )
Matches if none of the response headers is matched by one of the HeaderFilters.

CancelRequest

( object )
Declarative event action that cancels a network request.

RedirectRequest

( object )
Declarative event action that redirects a network request.

Properties of RedirectRequest

redirectUrl ( string )
Destination to where the request is redirected.

RedirectToTransparentImage

( object )
Declarative event action that redirects a network request to a transparent image.

RedirectToEmptyDocument

( object )
Declarative event action that redirects a network request to an empty document.

RedirectByRegEx

( object )
Redirects a request by applying a regular expression on the URL. The regular expressions use the RE2 syntax.

Properties of RedirectByRegEx

from ( string )
A match pattern that may contain capture groups. Capture groups are referenced in the Perl syntax ($1, $2, ...) instead of the RE2 syntax (\1, \2, ...) in order to be closer to JavaScript Regular Expressions.
to ( string )
Destination pattern.

SetRequestHeader

( object )
Sets the request header of the specified name to the specified value. If a header with the specified name did not exist before, a new one is created. Header name comparison is always case-insensitive. Each request header name occurs only once in each request.

Properties of SetRequestHeader

name ( string )
HTTP request header name.
value ( string )
HTTP request header value.

RemoveRequestHeader

( object )
Removes the request header of the specified name. Do not use SetRequestHeader and RemoveRequestHeader with the same header name on the same request. Each request header name occurs only once in each request.

Properties of RemoveRequestHeader

name ( string )
HTTP request header name (case-insensitive).

AddResponseHeader

( object )
Adds the response header to the response of this web request. As multiple response headers may share the same name, you need to first remove and then add a new response header in order to replace one.

Properties of AddResponseHeader

name ( string )
HTTP response header name.
value ( string )
HTTP response header value.

RemoveResponseHeader

( object )
Removes all response headers of the specified names and values.

Properties of RemoveResponseHeader

name ( string )
HTTP request header name (case-insensitive).
value ( optional string )
HTTP request header value (case-insensitive).

IgnoreRules

( object )
Masks all rules that match the specified criteria.

Properties of IgnoreRules

lowerPriorityThan ( integer )
If set, rules with a lower priority than the specified value are ignored. This boundary is not persisted, it affects only rules and their actions of the same network request stage.

RequestCookie

( object )
A filter or specification of a cookie in HTTP Requests.

Properties of RequestCookie

name ( optional string )
Name of a cookie.
value ( optional string )
Value of a cookie, may be padded in double-quotes.

ResponseCookie

( object )
A filter or specification of a cookie in HTTP Responses.

Properties of ResponseCookie

name ( optional string )
Name of a cookie.
value ( optional string )
Value of a cookie, may be padded in double-quotes.
expires ( optional string )
Value of the Expires cookie attribute.
maxAge ( optional double )
Value of the Max-Age cookie attribute
domain ( optional string )
Value of the Domain cookie attribute.
path ( optional string )
Value of the Path cookie attribute.
secure ( optional string )
Existence of the Secure cookie attribute.
httpOnly ( optional string )
Existence of the HttpOnly cookie attribute.

AddRequestCookie

( object )
Adds a cookie to the request or overrides a cookie, in case another cookie of the same name exists already. Note that it is preferred to use the Cookies API because this is computationally less expensive.

Properties of AddRequestCookie

cookie ( RequestCookie )
Cookie to be added to the request. No field may be undefined.

AddResponseCookie

( object )
Adds a cookie to the response or overrides a cookie, in case another cookie of the same name exists already. Note that it is preferred to use the Cookies API because this is computationally less expensive.

Properties of AddResponseCookie

cookie ( ResponseCookie )
Cookie to be added to the response. The name and value need to be specified.

EditRequestCookie

( object )
Edits one or more cookies of request. Note that it is preferred to use the Cookies API because this is computationally less expensive.

Properties of EditRequestCookie

filter ( RequestCookie )
Filter for cookies that will be modified. All empty entries are ignored.
modification ( RequestCookie )
Attributes that shall be overridden in cookies that machted the filter. Attributes that are set to an empty string are removed.

EditResponseCookie

( object )
Edits one or more cookies of response. Note that it is preferred to use the Cookies API because this is computationally less expensive.

Properties of EditResponseCookie

filter ( ResponseCookie )
Filter for cookies that will be modified. All empty entries are ignored.
modification ( ResponseCookie )
Attributes that shall be overridden in cookies that machted the filter. Attributes that are set to an empty string are removed.

RemoveRequestCookie

( object )
Removes one or more cookies of request. Note that it is preferred to use the Cookies API because this is computationally less expensive.

Properties of RemoveRequestCookie

filter ( RequestCookie )
Filter for cookies that will be removed. All empty entries are ignored.

RemoveResponseCookie

( object )
Removes one or more cookies of response. Note that it is preferred to use the Cookies API because this is computationally less expensive.

Properties of RemoveResponseCookie

filter ( ResponseCookie )
Filter for cookies that will be removed. All empty entries are ignored.

Events

onRequest

chrome.declarativeWebRequest.onRequest.addListener(function() {...});

Sample Extensions that use chrome.declarativeWebRequest

  • Event Page Example – Demonstrates usage and features of the event page
  • Catifier – Moar cats!