Mobile devices emulation with chromedriver

We all know how to automate the websites using selenium webdriver (Chromedriver).

Recently Chromedriver has been upgraded with new features which allow us to test website on various platforms like iPhones, iPads, Android etc.

We can easily configure chromedriver  to render the website in specific mobile device mode for testing purpose.

Below sample code can be used to launch website in iPhone 5. Please note that I have used chromedriver with version 2.2 as earlier versions were not working properly. To launch the website in other mobile platforms, you just need to change the device name in below code.

You can find out which devices are available for emulation in chrome developer tools window as shown in below image. To launch the mobile device mode, you need to press ctrl+shift+M keystroke. Please note that at the top there is a mobile device drop down where you can select various types of devices and see how your website will look like in it.

mobile device mode in chrome

 

package browsertests;

import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by sagar on 06-12-2015.
 */
public class MobileEmulationOnChrome {
    @Test
            public void launchChrome() {
        Map<String, String> mobileEmulation = new HashMap<String, String>();
       // mobileEmulation.put("deviceName", "Google Nexus 5");
        mobileEmulation.put("deviceName", "Apple iPhone 5");
        //mobileEmulation.put("deviceName", "Apple iPad");
        Map<String, Object> chromeOptions = new HashMap<String, Object>();
        chromeOptions.put("mobileEmulation", mobileEmulation);

        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
        System.setProperty("webdriver.chrome.driver","G:\\softwares\\selenium\\chromedriver2.2.exe");

        WebDriver driver = new ChromeDriver(capabilities);
        driver.get("https://softpost.org");
        driver.quit();
    }
}