Search code examples
rubyseleniumselenium-webdrivercapybarageckodriver

How to register Firefox driver with the customized profile to run with Capybara?


I tried to register selenium driver for Firefox through the below snippet. Actually i wanna set the customized user agent, but looks like after launching the browser, the user agent was not as I expected . Could anyone take a look at if there's something wrong? Thanks a lot

I'm running this with * GeckoDriver 0.24 * Firefox ver 67.0 * Capybara 3.18.0 * Selenium WebDriver gem 3.142.3

Capybara.register_driver :selenium do |app|
browser = ENV['BROWSER']
  browser_sym = browser.to_sym

  options = {
    browser: browser_sym,
  }
if browser == :firefox
    profile = Selenium::WebDriver::Firefox::Profile.new
    profile['browser.download.folderList'] = 2   
    profile['browser.helperApps.neverAsk.saveToDisk'] = 'text/csv'
    profile['dom.max_script_run_time'] = Configuration['browser']['wait_time']
    profile['general.useragent.override'] = 'customized user-agent' 
    profile['dom.max_chrome_script_run_time'] = Configuration['browser']['wait_time']
    profile['dom.max_script_run_time'] = Configuration['browser']['wait_time']
    options[:profile] = profile 
elsif browser == :chrome 
.....
end 
Capybara::Selenium::Driver.new(app, options)

Going to the launched browser and check the return result from Firefox Dev Console by command navigator.userAgent and it returns the default value not the customized user-agent.


Solution

  • To set the user agent in the Firefox profile your conditionals need to end up resolving to something like

    Capybara.register_driver :ff do |app|
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['general.useragent.override'] = 'Random User Agent'
    
      opts = Selenium::WebDriver::Firefox::Options.new(profile: profile)
    
      Capybara::Selenium::Driver.new(app, browser: :firefox, options: opts)
    end
    

    You can run it yourself using the code at https://gist.github.com/twalpole/2f69984a5c6063aab04ea25c0aa3d2ca