how to change user agent in selenium with .net

Luis Molina picture Luis Molina · Aug 1, 2013 · Viewed 17.1k times · Source

I want to test a web app written in .NET with different agents (iPhone, iPad, Android), I'm using NUnit for the tests and Selenium.

Anyone has a sample to change the agent (for example for iPad or iPhone) in Selenium with c# or VB?

Answer

Yi Zeng picture Yi Zeng · Aug 1, 2013

Example UA (You may need Google yourself to find the ones suit your purpose):

Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25

C# Firefox:

FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("general.useragent.override", "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25");
IWebDriver driver = new FirefoxDriver(profile);

C# Chrome:

ChromeOptions options = new ChromeOptions();
options.AddArgument("--user-agent=Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25");
IWebDriver driver = new ChromeDriver(options);

C# PhantomJS (untested code):

PhantomJSOptions options = new PhantomJSOptions();
options.AddAdditionalCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25");
IWebDriver driver = new PhantomJSDriver(options);

C# IE: Sorry, I don't think this is possible natively from Selenium.

Further reading: Set user agent using Selenium WebDriver C# and Ruby