Disable Google Analytics using javascript in Selenium

Viewed 4232

I'm using selenium to test a production site. The test activity screws with the analytics.

Can I disable the analytics using JavaScript after the page has loaded, via Selenium? I know I can execute JS via Selenium. The question is, how to disable the GA code?

3 Answers

By the power of --host-resolver-rules

let chrome = require("selenium-webdriver/chrome");
const chromeOptions = new chrome.Options();//.headless();
chromeOptions.addArguments('--host-resolver-rules=MAP www.google-analytics.com 127.0.0.1');
var $browser = new $driver.Builder()
    .forBrowser("chrome")
    .setChromeOptions(chromeOptions)

I learned it from Can I automate Chrome request blocking using Selenium-webdriver for Ruby? and it is working great.

Related