Skip to main content

Mobile Emulation in ChromeDriver

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

As it turns out there are not many options when it comes to running a Selenium node on a mobile device. So far selendroid.io seems the best solution but it never really worked in our Selenium infrastructure, so I was looking for an alternative and came across this website which shows how to use the Mobile Emulation feature of Chrome via Selenium. And this is how it works. Either define the name of the Mobile device as it is defined in Chrome:

$mobileEmulation = [
"deviceName" => "Google Nexus 5"
];

Or set some custom properties to define the target device:

$mobileEmulation = [
"deviceMetrics" => [
"width" => 360,
"height" => 640,
"pixelRatio" => 2.0,
],
"userAgent" => "Mozilla/5.0 (Linux; Android 4.2.1; DARKFULL Build/JOP40D) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.94 Mobile Safari/537.36"
];

Pass the configuration to the DesiredCapabilities configuration:

$desired_capabilities = \Facebook\WebDriver\Remote\DesiredCapabilities::chrome();
$desired_capabilities->setCapability('mobileEmulation',$mobileEmulation);

Build an RemoteWebDriver instance, navigate to the site and take a screenshoot:

$host = 'http://selenium-hub.loc:4444/wd/hub';
$driver = \Facebook\WebDriver\Remote\RemoteWebDriver::create($host, $desired_capabilities);
$driver->get('https://www.google.com');
$driver->takeScreenshot('/tmp/google.png');

Of course this is not a real replacement for testing on a mobile device but better than nothing. In the meantime I`ll dive deep into selendroid to figure out how to use it properly.