18

How can an extension intercept any requested URL to block it if some condition matches? (similar question for Firefox)

What permission needs to be set in manifest.json?

intika
  • 8,448
  • 5
  • 36
  • 55
user3833308
  • 1,132
  • 3
  • 14
  • 39
  • Please include enough information in this question so that it can be answerable if, say, link goes dead. It's fine and encouraged to link to related questions, but _this_ question should stand on its own. – Xan Jun 02 '15 at 08:25
  • 4
    @intika Accepted/improved your edit, nominated for reopening. – Xan Jun 02 '15 at 18:21

1 Answers1

40

JavaScript Code :

The following example illustrates how to block all requests to www.evil.com:

chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    return {cancel: details.url.indexOf("://www.evil.com/") != -1};
  },
  { urls: ["<all_urls>"] },
  ["blocking"]
);

The following example achieves the same goal in a more efficient way because requests that are not targeted to www.evil.com do not need to be passed to the extension:

chrome.webRequest.onBeforeRequest.addListener(
  function(details) { 
    return { cancel: true }; 
  },
  {urls: ["*://www.evil.com/*"]},
  ["blocking"]
);

Registering event listeners:

To register an event listener for a web request, you use a variation on the usual addListener() function. In addition to specifying a callback function, you have to specify a filter argument and you may specify an optional extra info argument.

The three arguments to the web request API's addListener() have the following definitions:

var callback = function(details) {...};
var filter = {...};
var opt_extraInfoSpec = [...];

Here's an example of listening for the onBeforeRequest event:

chrome.webRequest.onBeforeRequest.addListener(callback, filter, opt_extraInfoSpec);

Permission needed on manifest.json :

"permissions": [
  "webRequest",
  "webRequestBlocking",
  "tabs",
  "<all_urls>"
],

Extensions examples and help links:

Aaron Meese
  • 1,670
  • 3
  • 22
  • 32
intika
  • 8,448
  • 5
  • 36
  • 55