15

I'm trying to block some requests in a Chrome app.

I created a JavaScript listener that does this validation:

chrome.webRequest.onBeforeRequest.addListener(
    {
        urls: ["*://site.com/test/*"]
    },
    ["blocking"]
);

But the requests are not blocking. Did I miss something in this code?

My manifest:

"background": {
        "scripts": ["listener.js"],
        "persistent": true
    },
"permissions": ["tabs", "http://*/*"],
    "manifest_version": 2,
Chris McFarland
  • 6,059
  • 5
  • 43
  • 63
Berneck
  • 255
  • 1
  • 3
  • 7
  • 2
    If you [had opened the console for the background page](http://stackoverflow.com/questions/10257301/where-to-read-console-messages-from-background-js-in-a-chrome-extension/10258029#10258029), you would see the error messages about incorrect permissions. After fixing the permissions, you would see another error message that points out that the format of your `webRequest` API call is invalid. – Rob W Aug 10 '13 at 10:02
  • Using this link: [blocking requests in google chrome with pattern matching](https://stackoverflow.com/a/45784247/7487135) – Iman Bahrampour Aug 20 '17 at 18:17

2 Answers2

23

It looks like you misunderstood the meaning of "blocking" here.

https://developer.chrome.com/extensions/webRequest.html#subscription

If the optional opt_extraInfoSpec array contains the string 'blocking' (only allowed for specific events), the callback function is handled synchronously. That means that the request is blocked until the callback function returns. In this case, the callback can return a BlockingResponse that determines the further life cycle of the request.

To block a request (cancel it), return {cancel: true} in your event handler.

For example:

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

This will block all URLs matching *://site.com/test/*.

Also remember to declare both webRequest and webRequestBlocking permissions in your manifest.

Chris McFarland
  • 6,059
  • 5
  • 43
  • 63
方 觉
  • 4,042
  • 1
  • 24
  • 28
11

From Chrome 59 you can block specific requests from Network tab of developer tools itself.

https://developers.google.com/web/updates/2017/04/devtools-release-notes#block-requests

Right-click on the request in the Network panel and select Block Request URL. A new Request blocking tab pops up in the Drawer, which lets you manage blocked requests.

Sample

Asim K T
  • 16,864
  • 10
  • 77
  • 99
  • does not work for websocket. I.e. this does not work https://github.com/facebook/create-react-app/issues/2519#issuecomment-318867289 – rofrol May 08 '20 at 09:53