javaseleniumchrome-optionsmobile-emulator

Selenium - Mobile Emulation - how do I add user Agent to Chrome options while automating the emulator?


Below are the capabilities I added. I am getting a Google reCAPTCHA in my website which can be trespassed by adding user agent.

But even after the addition of user agent I am still getting the captcha. Is there another way to add it?

Map<String, String> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceName", "Pixel 2");

Map<String, Object> chromeOptions = new HashMap<>();
chromeOptions.put("mobileEmulation", mobileEmulation);

chromeOptions.put("args",
                  Arrays.asList("disable-bundled-ppapi-flash",
                  "disable-extensions",
                  "profile-directory=Default",
                  "disable-plugins-discovery",
                  "--user-agent=" + userAgent));

ChromeOptions co = new ChromeOptions();
co.addArguments("mobileEmulation="+mobileEmulation);

DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY,chromeOptions);

System.setProperty("webdriver.chrome.driver", RunConfig.CHROME_DRIVER_EXE);

driver = new ChromeDriver(capabilities);

Solution

  • You can use the below configuration for mobile emulation in the Chrome web browser:

    Map<String, Object> deviceMetrics = new HashMap<>();
    deviceMetrics.put("width", 1078);
    deviceMetrics.put("height", 924);
    deviceMetrics.put("pixelRatio", 3.0);
    Map<String, Object> mobileEmulation = new HashMap<>();
    mobileEmulation.put("deviceMetrics", deviceMetrics);
    mobileEmulation.put("userAgent", "Mozilla/5.0 (Linux; Android 8.0.0;" +
    "Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML,
    like Gecko) " +
    "Chrome/67.0.3396.99 Mobile Safari/537.36");
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
    driver = new ChromeDriver(chromeOptions);
    

    Instead of add argument setExpermentalOption to be used

    // co.addArguments("mobileEmulation=" + mobileEmulation);
    co.setExperimentalOption("mobileEmulation", mobileEmulation);