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 Screenshot2

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

Alex Skorkin
  • 4,264
  • 3
  • 25
  • 47
A7A
  • 51
  • 1
  • 3
  • you might want to check this out https://github.com/cyrus-and/chrome-remote-interface/wiki/Intercept-and-block-requests-by-URL – Abhishek Anand Jan 17 '18 at 07:21
  • Are you trying to use an extension to block requests? – guest271314 Jan 17 '18 at 07:26
  • Possible duplicate of [Blocking request in Chrome](https://stackoverflow.com/questions/18158297/blocking-request-in-chrome) – Vitaly Menchikovsky Jan 17 '18 at 07: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 – A7A Jan 17 '18 at 07:39
  • @VitalyMenchikovsky I tried this, I always seem to get an error when using chrome.webRequest it says chrome is undefined. – A7A Jan 17 '18 at 07:39
  • @guest271314 what do you mean? Sorry i dont get the question. – A7A Jan 17 '18 at 07:39
  • What do you mean by "block requests"? – guest271314 Jan 17 '18 at 07:40
  • @guest271314 I dont know really how to explain it. Best follow the screenshots hmm, ok try this: -in chrome open a new tab, then press CTRL+SHIFT+i -Navigate to the network tab -now go to any website and you will see the network tab page fill up, right click on one of them and you will have an option to block by URL, then this URL will be added to a filter at the bottom of the page. you can also use the + sign to add more URL with wildcards like in the screenshot – A7A Jan 17 '18 at 07:51
  • At Chromium/Chrome you can set a Policy, see [chrome Pop-up blocker when to re-check after allowing page](https://stackoverflow.com/questions/40282861/chrome-pop-up-blocker-when-to-re-check-after-allowing-page/) – guest271314 Jan 17 '18 at 07:54

1 Answers1

1

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

Marion
  • 1,074
  • 5
  • 10