4

How to block requests from a certain URL using JavaScript? For example, the manual way to do so on chrome will be to open the inspect page, go to network and block from there. But I need to block requests from certain URLs for an automated test that i am writing in JavaScript (using testcafe, if that offers any help).

Here are screenshots of manually blocking a request from chrome, I want to do the same thing automatically in my test/JavaScript: ScreenShot1

enter image description here

Thank you.

Edit: I tired following this post: Blocking request in Chrome but for some reason i always keep getting an error stating that chrome is undefined when I use chrome.webRequest

9
  • you might want to check this out github.com/cyrus-and/chrome-remote-interface/wiki/… Commented Jan 17, 2018 at 7:21
  • Are you trying to use an extension to block requests? Commented Jan 17, 2018 at 7:26
  • Possible duplicate of Blocking request in Chrome Commented Jan 17, 2018 at 7:29
  • @AbhishekAnand, I checked that already and tried it with changing the return pathname.match(/\.(css|png|svg)$/); to return pathname.match(/cdn/); to mach the blocking case in my screenshots. it didnt work Commented Jan 17, 2018 at 7:39
  • @VitalyMenchikovsky I tried this, I always seem to get an error when using chrome.webRequest it says chrome is undefined. Commented Jan 17, 2018 at 7:39

2 Answers 2

1

You can use the nock library, which allows you to intercept requests and process them as you wish.

Sign up to request clarification or add additional context in comments.

Comments

1

To achieve that you need to intercept & block the request originating from the response page to load ads. What you are looking for is the core principle of an ad-blocker which is possible with a browser extension.

so create a manifest.json with

{
    "manifest_version": 2,
    "name": "REQblock",
    "version": "2.3.4",
    "permissions": ["webRequest", "webRequestBlocking", "<all_urls>"],
    "background": {
      "scripts": ["script.js"]
    }    
} 

and then create script.json

function getBlacklistUrls(){    
    var  urls = [
    "*://cdn.sstatic.net/*",
    "*://*.twitter.com/*",
    "*://*.youtube.com/*"
    ];

    return urls; 
};

(async () => {
  var dummyCallback = function (details) {
    return {
      cancel: true
    };
  };

  var list = getBlacklistUrls();
  var blockedUrls = { urls: list };

  //Add Listener
  chrome.webRequest.onBeforeRequest
    .addListener(dummyCallback,blockedUrls,["blocking"]);
})();

The above chrome extension will block all url returning from getBlacklistUrls().

The result will come something like this enter image description here

If you still don't understand what chrome extensions are and how to load & enable check my ad-blocker AdvertShield at github and follow the wiki as how to install it.

Update: 2024

While the manifest version 2 is out dated your chrome browser might complain about it, to upgrade we can use the manifest version 3 and things are little different here as there is no javascript involved and just a pair of two json below will block a bunch of url for you.

manifest.json

{
    "manifest_version": 3,
    "name": "AdvertShield",
    "version": "3.1",
    "description": "AdvertShield is a URL/Request Blocking Extension by (c)killercodes.github.io \n This will blaock all the ads coming from a list",
    "permissions": ["webRequest", "declarativeNetRequest","declarativeNetRequestFeedback"],
    "host_permissions" :["http://*/*", "https://*/*"], 

    "declarative_net_request" : {
        "rule_resources" : [{
          "id": "ruleset_1",
          "enabled": true,
          "path": "block_rules.json"
        }]
    }
}

block_rules.json

[
    {
      "id": 1,
      "priority": 1,
      "action": { "type": "block" },
      "condition": {"urlFilter": "doubleclick.net", "resourceTypes": ["csp_report", "font", "image", "main_frame", "media", "object", "other", "ping", "script","stylesheet", "sub_frame", "webbundle", "websocket", "webtransport", "xmlhttprequest"] }
    },
    {
      "id": 2,
      "priority": 1,
      "action": { "type": "block" },
      "condition": { "urlFilter": "googleadservices.com", "resourceTypes": ["csp_report", "font", "image", "main_frame", "media", "object", "other", "ping", "script","stylesheet", "sub_frame", "webbundle", "websocket", "webtransport", "xmlhttprequest"]  }
    },
    {
      "id": 3,
      "priority": 2,
      "action": { "type": "block" },
      "condition": { "urlFilter": "googlesyndication.com", "resourceTypes": ["csp_report", "font", "image", "main_frame", "media", "object", "other", "ping", "script","stylesheet", "sub_frame", "webbundle", "websocket", "webtransport", "xmlhttprequest"]  }
    },
    {
      "id": 4,
      "priority": 1,
      "action": { "type": "redirect", "redirect": { "url": "https://example.com" } },
      "condition": { "urlFilter": "twitter.com", "resourceTypes": ["main_frame"] }
    }
]

For this to work you need to put this in a folder and enabled Developer mode in chrome://extensions/ then click load unpacked and browse to the folder.

If this is all confusing look for https://github.com/Killercodes/Advert-Shield/tree/Version-3.0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.