How to modify user-agent in Chrome for automated web testing using Appium on LambdaTest ?
Not only user-agent, you can add custom hеadеrs to your tеsts and bypass firеwall rеstrictions using the customHeaders
capability of LambdaTest.
Create a Map and add the custom headers (e.g. user-agent
) and integrate it into ltOptions
(used for LambdaTest configuration).
Shown below is an example for iOS (Appium 2.x):
/* Retrieve keys from https://accounts.lambdatest.com/security */
String userName = System.getenv("LT_USERNAME") == null ? "LT_USERNAME" : System.getenv("LT_USERNAME");
String accessKey = System.getenv("LT_ACCESS_KEY") == null ? "LT_ACCESS_KEY" : System.getenv("LT_ACCESS_KEY");
String grid_url = System.getenv("LT_GRID_URL") == null ? "mobile-hub.lambdatest.com" : System.getenv("LT_GRID_URL");
private IOSDriver driver;
@BeforeClass
public void setUp() throws MalformedURLException
{
/* Appium 2.x */
DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> ltOptions = new HashMap<String, Object>();
ltOptions.put("build", "Build Name");
ltOptions.put("name", "Name");
ltOptions.put("w3c", true);
ltOptions.put("platformName", "iOS");
ltOptions.put("deviceName", "iPhone 13*");
ltOptions.put("platformVersion", "15");
ltOptions.put("isRealMobile", true);
ltOptions.put("network", false);
ltOptions.put("visual", true);
ltOptions.put("devicelog", true);
ltOptions.put("autoAcceptAlerts", true);
ltOptions.put("network", true);
/* Browser Combination */
ltOptions.put("browserName", "Safari");
ltOptions.put("browserVersion", "latest");
/* Setup custom header - user agent in this case */
final Map<String, String> CUSTOM_HEADERS_VALUES = new HashMap<>() {{
put("user-agent", "custom-user-agent");
}};
ltOptions.put("customHeaders", CUSTOM_HEADERS_VALUES);
capabilities.setCapability("lt:options", ltOptions);
String hub = "https://" + userName + ":" + accessKey + "@" + grid_url + "/wd/hub";
/* Appium 1.x*/
/* driver = new AppiumDriver(new URL(hub), capabilities); */
/* Appium 2.x */
driver = new IOSDriver(new URL(hub), capabilities);
Here are the changes to set custom headers:
ltOptions.put("network", true);
final Map<String, String> CUSTOM_HEADERS_VALUES = new HashMap<>()
{
{
put("user-agent", "custom-user-agent");
}
};
ltOptions.put("customHeaders", CUSTOM_HEADERS_VALUES);
Once you have modified the headers (e.g. browser user-agent in this case), navigate to the website https://useragentstring.com/ to verify if the user-agent modification is successful or not.
For more information, please visit Custom Headers Capability documentation on LambdaTest.