Paul Irish
Paul Irish

Reputation: 49242

Emulating mobile in ChromeDriver

If you're using WebDriver with Chrome (via Chromedriver) you may want to emulate mobile viewport characteristics. Similarly, you may want to automate tests on desktop without having to use a proper Chrome on Android setup.

How do you do that?

Upvotes: 16

Views: 25952

Answers (4)

Rohan Ghosh
Rohan Ghosh

Reputation: 1

There are 2 ways to use mobile emulation in Chrome. Providing 'deviceName' or device 'height', 'width', 'pixelRatio' at the 'setExperimentalOption' method of ChromeOptions. Explained details in this video.

Upvotes: 0

Paul Irish
Paul Irish

Reputation: 49242

The mobile_emulation capability was added to ChromeDriver in 2.11

Full documentation: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation

My notes below:

Creating a driver in Python with the mobile_emulation capability options:

 driver = self.CreateDriver(
        mobile_emulation = {
            'deviceMetrics': {'width': 360, 'height': 640, 'pixelRatio': 3}})

Currently you can emulate devicepixelratio, useragent, viewport height and width.

Possible properties for the mobile_emulation dict:

  • deviceName : if used, must be the only property. Matches a device preset in Chrome (e.g. 'Google Nexus 5').
  • deviceMetrics: a dict that can include width (int), height (int), pixelRatio (double) as shown above.
  • userAgent: a string to spoof at the request header and navigator object.

Upvotes: 15

Emilis Prascienius
Emilis Prascienius

Reputation: 71

This is in the latest official chromedriver build (2.11).

Example in java:

final DesiredCapabilities dc = DesiredCapabilities.chrome();
dc.setCapability(ChromeOptions.CAPABILITY, new ChromeOptions() {
{
    setExperimentalOption("mobileEmulation", new HashMap<String, Object>() {
            {
                put("deviceName", "Google Nexus 5");
            }
        });
    }
});

ChromeDriver driver = new ChromeDriver(dc);

Upvotes: 7

Oliver Schupp
Oliver Schupp

Reputation: 423

The mobileEmulation option is implemented in the last ChromeDriver release (v 2.11). Using WebDriverJs you have to add it as property to the capabilities object.

var webdriver = require('selenium-webdriver');
var capabilities = {
  browserName: 'chrome',
  chromeOptions: {
    mobileEmulation: {
      deviceName: 'Apple iPhone 5'
    }
  }
};
var
  driver = new webdriver
  .Builder()
  .withCapabilities(capabilities)
  .build();


driver.get('http://google.com');

var bool = false;
setTimeout(function () {
  bool = true;
}, 9000);
driver.wait(function() {
 return bool;
}, 10000);

driver.quit();

Upvotes: 6

Related Questions