Search code examples
seleniumselenium-webdriverintegration-testingbrowsermob

How can I block third-party scripts on Selenium tests?


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.


Solution

  • 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)
    }