follow me icons

Tuesday, September 28, 2010

Changing User-agent profile in firefox through Selenium Webdriver

Firefox has an add-on called user-agent switcher which is used to switch the browser user agent so that the server thinks the query comes from a mobile devices.

There are times when we need to be able to switch user agent automatically from the cucumber test. This is when we need to test that the apache config can redirect the site correctly to the mobile URL.

We can do this by overriding the default firefox user agent profile to use the required user agent. Firefox has an attribute called general.useragent.override which we can put any user agent profile that we want.

Below is the code on how to do it.

class Capybara::Driver::Selenium
def self.driver
unless @driver
profile = Selenium::WebDriver::Firefox::Profile.new

profile["general.useragent.override"]
= "Mozilla/5.0 (iPhone; U; CPU iPhone" +
" OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18" +
"(KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"

@driver = Selenium::WebDriver.for(:firefox, :profile => profile)

at_exit do
@driver.quit
end
end
@driver
end
end



If you want to see all of the availables firefox profile that we can override, you can type the following command on the firefox URL text field "about:config".

Please see below for user agent settings for iPhone, iPad, Nokia, Android:

iPad_UA=Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10

iPhone_UA=Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16

N95_UA=Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaN95/10.0.010; Profile/MIDP-2.0 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413

LG-G850=LG-G850 V100 UP.Browser/6.2.2 (GUI) MMP/1.0 Profile/MIDP-1.0 Configuration/CLDC-1.0

ANDROD_EMULATOR=Mozilla/5.0 (Linux; U; Android 1.0; en-us; generic) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2

X10_UA="Mozilla/5.0 (Linux; U; Android 1.6; en-gb; SonyEricssonX10i Build/R1FA016) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1"

2 comments:

  1. As of Capybara 0.4.0, you would need to use the following code

    Capybara.register_driver :selenium do |app|
    profile = Selenium::WebDriver::Firefox::Profile.new

    profile["general.useragent.override"]
    = "Mozilla/5.0 (iPhone; U; CPU iPhone" +
    " OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18" +
    "(KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"

    Capybara::Driver::Selenium.new(app, :browser => :firefox, :profile => profile)
    end

    ReplyDelete
  2. can you more elaborate in detail> i want run the selenium webdriver test in firefox iphone user agent. is that possible?

    ReplyDelete