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?
Here are few options you might try. Some were taken from this blog post - Exclude Selenium WebDriver traffic from Google Analytics.
Option 0: Avoid testing live production sites
Ideally automated Selenium UI testing is preferred to test against some kind of testing environment, instead of mess around live production databases. As live production sites only need some manual exploratory/smoke testing. In this case, when setting up the testing environment, use a different Google Analytics tracker or even avoid using Google Analytics.
Option1: Disable JavaScript
Since Google Analytics tracking is done by executing a snippet of JavaScript code, disable JavaScript in browsers would do. But this isn't practical, because surely this will impact the functionality of the site.
Option2: Set user agent and exclude user agent
Set a special testing user agent when start WebDriver, then in your source, use JavaScript to exclude that user agent.
For example, your GA should be:
if (user agent != your special testing user agent) {
your GA code
}
Option3: Exclude IP/ISP
Set it in your GA's admin settings
Option4: Opt-out plugins
Start your WebDriver a GA opt-out plugin (only possible with ChromeDriver and FirefoxDriver). Google Analytics Opt out Add ons
Option5: Custom variables (cookies) with JavaScript
See "Set a Cookie with JavaScript" section in Best Ways to Exclude Internal Traffic in Google Analytics
Option6: Use a proxy like BrowserMob Proxy
BrowserMob Proxy allows manipulating HTTP requests and responses, capturing HTTP content, and exporting performance data as a HAR file. It supports blacklisting which can be used as a way of blocking data sent to Google Analytics.
require 'browsermob/proxy'
require 'selenium-webdriver'
server = BrowserMob::Proxy::Server.new("./browsermob-proxy-2.1.4/bin/browsermob-proxy", :log => true)
server.start
proxy = server.create_proxy
proxy.blacklist("https?:\/\/www\.google-analytics\.com\/.*", 404)
profile = Selenium::WebDriver::Firefox::Profile.new
profile.proxy = proxy.selenium_proxy
driver = Selenium::WebDriver.for :firefox, :profile => profile
proxy.new_har "browsermob"
driver.get 'http://yizeng.me/'
har = proxy.har
har.entries.first.request.url
har.save_to "./browsermob.har"
proxy.close
driver.quit
Option7: Remove GA code using Selenium JavaScriptexecutor
Your idea, but not sure if this is possible, once GA code is loaded, it's been executed, using Selenium to remove to code has to be somehow after that?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With