Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the BSD License.
©2011 Google
Warning: This API is still under development. It is only available for Chrome users on the dev early release channel. Learn more.
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.
You must declare the "declarative" and 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": [
"declarative",
"declarativeWebRequest",
"*://*.google.com"
],
...
}
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.
See chrome.events.Event.addRules().