Setting Capabilities to Use Selenium WebDriver for Mobile Testing

If you visit: http://www.i4info.info

and then: http://www.i4info.info/history

on your mobile phone, you will get a User Agent.

Anytime a mobile device make a request for a webpage, it sends the User Agent in the headers of the HttpGet, HttpPost request. This in turn lets the server know which page to serve. You may allow WebDriver to test the appropriate environment by setting the Capabilities for Selenium WebDriver appropriately. Here is a class that will help with handling the user agent and setting the appropriate capability for the browser you are testing with.


import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.DesiredCapabilities;

public class UserAgentHandler {
	public void handle(String useragent) {
		if (useragent != null && !useragent.trim().isEmpty()) {
			handleFirefox(useragent);
			handleChrome(useragent);
			handlePhantom(useragent);
		}
	}

	private void handleFirefox(String useragent) {
		try {
			DesiredCapabilities dc = DesiredCapabilities.firefox();
			FirefoxProfile profile = new FirefoxProfile();
			profile.setPreference("general.useragent.override", useragent);
			dc.setCapability(FirefoxDriver.PROFILE, profile);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void handleChrome(String useragent) {
		try {
			DesiredCapabilities dc = DesiredCapabilities.chrome();
			ChromeOptions chromeOptions = new ChromeOptions();
			chromeOptions.addArguments("--user-agent=" + useragent);
			dc.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void handlePhantom(String useragent) {
		try {
			DesiredCapabilities dc = DesiredCapabilities.phantomjs();
			dc.setJavascriptEnabled(true);
			dc.setCapability("phantomjs.page.settings.userAgent", useragent);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}