4

My Selenium tests are being slowed by third-party scripts that are not necessary to the tests.

How can I block them? Preferably I'd like to block requests to everywhere but localhost.

WoodenKitty
  • 6,101
  • 8
  • 47
  • 70

1 Answers1

4

Solutions offered elsewhere online are:

  • Block unwanted domains (e.g., *.facebook.com) by editing your hostfiles.
  • Route all your tests through BrowserMob which can be configured to filter requests.

Both options seemed like overkill to me. Editing the host files affects your whole system, and using BrowserMob introduces new problems.

Here's another way: Use a PAC file to configure the browser to connect to localhost directly, and attempt to connect to everything else through an unavailable proxy.

Selenium code (Java):

DesiredCapabilities capabilities = DesiredCapabilities.chrome();
Proxy proxy = new Proxy();
proxy.setProxyType(Proxy.ProxyType.PAC);
proxy.setProxyAutoconfigUrl("http://localhost:8080/my-pac-file.pac");
capabilities.setCapability("proxy", proxy);
ChromeDriver driver = new ChromeDriver(INSTANCE, capabilities);

The PAC file:

function FindProxyForURL(url, host) {
    if (host.toLowerCase() === "localhost"){
      return "DIRECT"; // whitelisted
    }
  return "PROXY 127.0.0.1:9876"; // blocked (bad proxy)
}
WoodenKitty
  • 6,101
  • 8
  • 47
  • 70
  • Is there a specific folder the PAC file should be located in? Does this location vary with different browsers? – Grasshopper Oct 19 '16 at 07:05
  • @Grasshopper Anywhere that it can be retrieved with a HTTP request. – WoodenKitty Oct 19 '16 at 08:57
  • Note (at least with the Chrome driver) you can use [data URIs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) so that you don't have to host an actual file anywhere, but that `FindProxyForURL` function can be stored in a string variable in code – Matt Thomas Mar 26 '19 at 15:07