Run Selenium Tests on Chromedriver

Check your websites on Real Chrome browsers. Run Selenium Tests on Chromedriver on Real Device Cloud

Get Started free
Home Guide How to run Selenium tests on Chrome using ChromeDriver?

How to run Selenium tests on Chrome using ChromeDriver?

By Sonal Dwivedi, Community Contributor -

Google Chrome dominates the browser market with a massive 64% global market share. With several useful features, it is one of the most preferred browsers in the world. Given its importance and usage, testing all websites on Chrome becomes crucial.

This article will explain how to perform Selenium tests on a Chrome browser using ChromeDriver. But before that, let’s understand what ChromeDriver is and how users can configure it on their systems.

What is a Selenium ChromeDriver?

A ChromeDriver is a standalone server or a separate executable used by Selenium WebDriver to control Chrome. Running Selenium test scripts on the Google Chrome browser is impossible without ChromeDriver. One can easily initialize the object of ChromeDriver using the following command:

WebDriver driver = new ChromeDriver

How to download ChromeDriver for Selenium?

You can download ChromeDriver for Selenium as per the ChromeDriver version using its official website. Here are the steps given below:

Steps to download ChromeDriver version 115 and above

Step 1. Navigate to ChromeDriver official site for downloading the latest ChromeDriver. Download ChromeDriver version 115

Step 2. For Chrome browser version 115 and above, click on “the Chrome for Testing availability dashboard” which will navigate to Chrome for Testing Dashboard. Chrome for Testing availability dashboard

Step 3. This page has various versions for Stable, Beta, Dev and Canary releases for Windows, Mac and Linux operating system. Click on Stable link and look for ChromeDriver Win32 or Win64 (based on the Windows OS system type). ChromeDriver 64

Step 4. Open the URL in the new browser window and ChromeDriver will be downloaded in zip format. Extract the content and move it to the desired location. (Preferably at the root location of the automationproject). chromedriver path

Steps to download ChromeDriver version 114 and below

Step 1. Navigate to ChromeDriver official site which lists all the latest and previous versions of ChromeDriver.

Step 2. Based on the Chrome browser version available on the system download the respective ChromeDriver. Assuming current Chrome browser version to be 114, click on “ChromeDriver 114.0.5735.90”. This page will navigate to the download section which has drivers for Mac, Linux, and Windows.

Step 3. Assuming the current system is Windows, click on “chromedriver_win32.zip”. Chromedriver 114 windows

Step 4. ChromeDriver will be downloaded in zip format. Extract the content and move it to the desired location. (Preferably at the root location of the automation project).

Now, we have the desired ChromeDriver downloaded depending on our Chrome browser version, let us see the 2 ways by which we can configure ChromeDriver via environment and System.setProperty() method of Java.

BrowserStack Automate Banner 6

How to configure ChromeDriver?

You can configure ChromeDriver using different methods

Steps to configure ChromeDriver via Environment Variable

On Windows operating systems, we can declare system level variables by using Environment variables. Below steps will help you set up the environment variable for Chrome Driver. Whenever an instance of the WebDriver is created in Selenium script, it will automatically detect the path of the ChromeDriver from the system variables.

Step 1. After the ChromeDriver executable file is extracted and moved to the desired location, copy that location to set its path in System’s environment variables.

Step 2. Open Environment variable pop up by directly searching for “Environment Variables” from Windows Search. This will open “System Properties” pop up. Click on the “Environment Variables” button. Configure Chrome with Environment Variable

Step 3. On Environment Variables pop-up’s System Variables section, click on Path variable and click on the Edit button.  Edit Path Variable to configure ChromeDriver

Step 4. On the Edit environment variable pop-up, click on the “New” button and add the ChromeDriver executable location. Click on OK to save the configuration. New Path variable to configure chrome

Step 5. Now whenever we create an instance of ChromeDriver in the Selenium script, it will automatically detect the ChromeDriver path from the system variable.

driver = new ChromeDriver();

This will automatically detect the ChromeDriver path from the system variable.

Configure ChromeDriver via System.setProperty method

ChromeDriver can also be configured by explicitly specifying the ChromeDriver path in the test script.

System.setProperty accepts key value pair where key would be “webdriver.chrome.driver” and value would be the path of the ChromeDriver exe path.

System.setProperty("webdriver.chrome.driver", "D:\\BStackDemo\\chromedriver.exe");

Steps for macOS users:

  1. Go to the terminal and type the command: sudo nano /etc/paths
  2. Enter the password
  3. At the bottom of the file, add the path of your ChromeDriver
  4. Type Y to save
  5. To exit press Control + C

Talk to an Expert

Chrome-Specific Functionalities in Selenium

Selenium provides several Chrome-specific functionalities to enhance browser automation. Utilizing these Chrome-specific functionalities can significantly enhance your Selenium testing framework, making it more efficient and capable of handling a wide range of scenarios. Whether you’re automating tests, scraping data, or performing UI testing, these features can provide added flexibility and power.

Here are some key features and capabilities you can leverage when working with Chrome in Selenium:

1. ChromeDriver

Selenium interacts with Chrome through ChromeDriver, which acts as a bridge. Make sure to download the appropriate version matching your Chrome browser.

2. Chrome Headless Mode

Running Chrome in headless mode with Selenium allows you to execute tests without a graphical user interface (GUI). This can speed up the execution of tests and is particularly useful for environments where a display is not available, such as CI/CD pipelines or server environments. Run Chrome in headless mode for faster execution without opening the browser window. Here’s how you run chrome in headless mode:

public class HeadlessChromeExample {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");



        ChromeOptions options = new ChromeOptions();

        options.addArguments("--headless"); // Enable headless mode

        options.addArguments("--disable-gpu"); // Disable GPU hardware acceleration



        WebDriver driver = new ChromeDriver(options);

        driver.get("https://www.example.com");



        // Perform operations...

        
        driver.quit();

    }

}

3. ChromeOptions

Use ChromeOptions to customize Chrome browser settings, such as enabling/disabling extensions, setting window size, or managing profiles by creating an instance of ChromeOptions for setting ChromeDriver-specific capabilities. You can then pass the ChromeOptions object into the ChromeDriver constructor:

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;



public class ChromeOptionsExample {

    public static void main(String[] args) {

        // Set the path to the ChromeDriver executable

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");



        // Set Chrome options

        ChromeOptions options = new ChromeOptions();

        options.addArguments("--start-maximized"); // Start maximized

        options.addArguments("--disable-infobars"); // Disable infobars



        // Initialize WebDriver

        WebDriver driver = new ChromeDriver(options);



        // Open a webpage

        driver.get("https://www.example.com");



        // Close the browser

        driver.quit();

    }

}

4. Browser Profiles

Using browser profiles in Selenium with Chrome allows you to customize your testing environment by retaining specific settings, cookies, and session data. This can be especially useful for automating tests that require logged-in states or particular configurations. You can use existing user profiles to retain cookies and settings across sessions.

public class BrowserProfileExample {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");



        String userDataDir = "C:/Users/<YourUsername>/AppData/Local/Google/Chrome/User Data";

        String profileName = "Profile 1";



        ChromeOptions options = new ChromeOptions();

        options.addArguments("user-data-dir=" + userDataDir);

        options.addArguments("profile-directory=" + profileName);



        WebDriver driver = new ChromeDriver(options);

        driver.get("https://www.example.com");



        // Perform operations...
        

        driver.quit();

    }

}

5. Handling Pop-ups and Alerts

Handling pop-ups and alerts in Selenium when using Chrome involves specific methods to interact with JavaScript alerts, confirmation boxes, and prompts. You can switch to and handle alerts that appear in the browser.

public class HandleAlertExample {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");



        WebDriver driver = new ChromeDriver();

        driver.get("https://www.example.com");



        // Trigger an alert (e.g., via JavaScript or a button click)

        driver.findElement(By.id("triggerAlertButton")).click();



        // Switch to the alert

        Alert alert = driver.switchTo().alert();

        System.out.println("Alert text: " + alert.getText());

        alert.accept(); // Accept the alert



        driver.quit();

    }

}

6. Executing JavaScript

Executing JavaScript in Chrome using Selenium is a powerful way to interact with web pages beyond the typical WebDriver methods. You can manipulate the DOM, trigger events, or retrieve data from the page. You can execute JavaScript commands within the context of the loaded page.

import org.openqa.selenium.JavascriptExecutor;



public class ExecuteJavaScriptExample {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");



        WebDriver driver = new ChromeDriver();

        driver.get("https://www.example.com");



        // Execute JavaScript

        JavascriptExecutor js = (JavascriptExecutor) driver;

        js.executeScript("alert('Hello, World!');");



        // Close the alert

        driver.switchTo().alert().accept();



        driver.quit();

    }

}

7. Performance Logging

Performance logging in Chrome using Selenium allows you to capture detailed performance metrics and network activity while running your tests. This can be especially useful for analyzing page load times, resource loading, and overall performance. You can enable performance logging to capture metrics.

import org.openqa.selenium.logging.LogEntries;

import org.openqa.selenium.logging.LogEntry;

import org.openqa.selenium.logging.LogType;



public class PerformanceLoggingExample {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");



        ChromeOptions options = new ChromeOptions();

        options.setCapability("goog:loggingPrefs", Map.of("performance", "ALL"));



        WebDriver driver = new ChromeDriver(options);

        driver.get("https://www.example.com");



        LogEntries logs = driver.manage().logs().get(LogType.PERFORMANCE);

        for (LogEntry log : logs) {

            System.out.println(log.getMessage());

        }



        driver.quit();

    }

}

8. Chrome DevTools Protocol (CDP)

The Chrome DevTools Protocol (CDP) provides a powerful interface for interacting with the Chrome browser’s debugging features. In Selenium, you can use CDP to access advanced functionalities, such as performance metrics, network interception, and more.

CDP provides access to features that are not available through the standard Selenium WebDriver API. You can capture detailed performance metrics to optimize web applications.

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.openqa.selenium.devtools.DevTools;

import org.openqa.selenium.devtools.v93.browser.Browser;

import org.openqa.selenium.devtools.v93.network.Network;

import org.openqa.selenium.devtools.v93.performance.Performance;

import org.openqa.selenium.WebDriver;



import java.util.Optional;



public class CDPExample {

    public static void main(String[] args) {

        // Set the path to the ChromeDriver executable

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");



        // Set Chrome options

        ChromeOptions options = new ChromeOptions();

        options.addArguments("--remote-debugging-port=9222"); // Enable debugging



        // Initialize WebDriver

        WebDriver driver = new ChromeDriver(options);



        // Access the DevTools interface

        DevTools devTools = ((ChromeDriver) driver).getDevTools();

        devTools.createSession();



        // Enable network tracking

        devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));



        // Intercept network requests

        devTools.addListener(Network.requestWillBeSent(), request -> {

            System.out.println("Request URL: " + request.getRequest().getUrl());

        });



        // Start capturing performance metrics

        devTools.send(Performance.enable());



        // Open a webpage

        driver.get("https://www.example.com"); // Replace with your URL



        // Capture performance metrics

        devTools.addListener(Performance.metrics(), metrics -> {

            System.out.println("Performance metrics: " + metrics.getMetrics());

        });



        // Close the browser

        driver.quit();

    }

}

9. Geolocation

Handling geolocation in Selenium with Chrome allows you to simulate different geographic locations for testing purposes. This can be particularly useful for applications that rely on location-based services. Here’s how you can manage geolocation settings in Selenium with Chrome.

To simulate geolocation, you need to set up Chrome options and use the Chrome DevTools Protocol (CDP) to manipulate the geolocation settings.

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.openqa.selenium.devtools.DevTools;

import org.openqa.selenium.devtools.v93.geolocation.Geolocation;

import org.openqa.selenium.WebDriver;



import java.util.Optional;



public class GeolocationExample {

    public static void main(String[] args) {

        // Set the path to the ChromeDriver executable

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");



        // Set Chrome options

        ChromeOptions options = new ChromeOptions();

        options.addArguments("--remote-debugging-port=9222"); // Enable debugging



        // Initialize WebDriver

        WebDriver driver = new ChromeDriver(options);



        // Access the DevTools interface

        DevTools devTools = ((ChromeDriver) driver).getDevTools();

        devTools.createSession();



        // Set geolocation

        double latitude = 37.7749;  // Example: San Francisco

        double longitude = -122.4194;

        double accuracy = 100;       // Optional accuracy in meters



        // Send geolocation data

        devTools.send(Geolocation.setGeolocationOverride(Optional.of(latitude), Optional.of(longitude), Optional.of(accuracy)));



        // Open a webpage that uses geolocation

        driver.get("https://www.example.com"); // Replace with a URL that requests geolocation



        // Close the browser

        driver.quit();

    }

}

10. Extensions in Chrome

Using Chrome extensions in Selenium can enhance your automation capabilities by allowing you to interact with additional browser features. To load a Chrome extension in Selenium, you can specify the path to the extension file (usually a .crx or unpacked extension directory) using ChromeOptions.

Use options.addExtensions() to load a .crx file or unpacked directory. Ensure that the path is correct. Using Chrome extensions in Selenium allows you to enhance your automated tests by adding extra functionalities to the browser.

You might load an extension for:

  • Ad blocking to test ad-free browsing experiences.
  • Custom tools for web scraping or data extraction.
  • Accessibility features that enhance usability for users with disabilities.
import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;



import java.nio.file.Paths;



public class ChromeExtensionExample {

    public static void main(String[] args) {

        // Set the path to the ChromeDriver executable

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");



        // Set Chrome options

        ChromeOptions options = new ChromeOptions();

        

        // Specify the path to the extension

        String extensionPath = "path/to/your/extension.crx"; // or path to unpacked extension directory

        options.addExtensions(Paths.get(extensionPath).toFile());



        // Initialize WebDriver with the specified options

        WebDriver driver = new ChromeDriver(options);



        // Open a webpage

        driver.get("https://www.example.com"); // Replace with your URL



        // Your code to interact with the page and extension



        // Close the browser

        driver.quit();

    }

}

Steps to run Selenium Tests on Chrome Browser

Let’s discuss how to run Selenium scripts on a Chrome browser using ChromeDriver.

  1. In Eclipse or any IDE, create a Java project and add Selenium Java jars in the Java build path section.
  2. Create a Java class file and add the below code to launch BStackDemo application on Chrome browser.
  3. Set the properties by specifying the type of driver to be used along with its path describing where it is stored.
  4. Initialize the object of the ChromeDriver. This helps in launching the Chrome browser.
  5. To navigate to a particular URL, use the driver.get() method. One can also locate certain web elements using specific locators. To know more about locating elements in Selenium, refer to this detailed guide on Locators in Selenium.

Now let’s consider a test case example wherein we want to perform 2 simple steps:

  1. Open Chrome Browser
  2. Go to www.bstackdemo.com

Did you know: There are more than 98 Chrome Browser versions to test on. Don’t miss out on testing across!

Refer to the code snippet below to get a better sense of executing the steps mentioned above:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ChromeTest {

public static void main(String args[]) {

WebDriver driver;

//Setting system properties of ChromeDriver 
System.setProperty("webdriver.chrome.driver", "D:\\BStackDemo\\chromedriver.exe");

//Creating an object of ChromeDriver
driver = new ChromeDriver();

//launching the specified URL 
driver.get("https://bstackdemo.com/");
}
}

If you are configuring ChromeDriver via the environment variable, delete the System.setProperty() line from the above code and it should work.

Run Selenium Tests using ChromeDriver

How to run Selenium Tests on Real Chrome Browser using Automate

Here’s are the steps to run Selenium Tests on Real Chrome Browsers with BrowserStack Automate using BrowserStack SDK:

Step 1. Download BrowserStack Project Zip from the GitHub page.

Step 2. Once it is downloaded, unzip it in a desired location in your local system.

folder structure

Step 3. Import the project in Eclipse via File-> Import -> General -> Projects from Folder or Archive in Eclipse.

import in eclipse

Step 4. Once the project is imported it should have a structure like below. Open browser.yml file which contains all the required capabilities to run the tests on BrowserStack platform.

eclipse structure

Step 5. Set username and password in the browserstack.yml file available at the root directory.

Step 6. You can run the test cases on multiple device and browser combinations available at the BrowserStack cloud. Select the required combinations from the Selection List.

devices

Step 7. Copy and replace the platforms object in the browserstack.yml file like below.

platforms:

- os: Windows

osVersion: 10

browserName: Chrome

browserVersion: latest
- os: OS X

osVersion: Monterey

browserName: Safari

browserVersion: 15.6
 - deviceName: iPhone 13

osVersion: 15

browserName: Chromium

deviceOrientation: portrait

This is for running the test cases on 3 combinations. If you wish to run only on a single device you may edit the platforms accordingly.

Step 8. In the Eclipse Marketplace, search for BrowserStack > click Install > Finish.

eclipse marketplace

Step 9. Add the above ChromeTest program under src/test/java folder and com.browserstack package. This class should extend SeleniumTest as it has the setup and teardown methods. The simplified code is as below using BrowserStack SDK.

package com.browserstack;

import com.browserstack.SeleniumTest;

import org.testng.Assert;

import org.testng.annotations.Test; 

public class ChromeTest extends SeleniumTest { 

   @Test

   public void launchChrome() {

         // launching the specified URL

         driver.get("https://bstackdemo.com/");

         Assert.assertEquals(driver.getTitle(), "StackDemo");

   }

}

Step 10. Run ChromeTestas TestNG test and view the test result on Automate dashboard.

Automate Dashboard

Best Practices for using Selenium ChromeDriver

Here are the key best practices to follow when using Selenium ChromeDriver:

  1. Cross-browser compatibility: Different browsers render web pages differently. Testing on real browsers ensures that the web application functions correctly across multiple browsers such as Chrome, Firefox, Safari and Microsoft Edge. To provide consistent experience across all the platforms, it is mandatory to test the web applications on different browsers.
  2. Parallel Testing: With BrowserStack’s Automate platform one can easily test the web application across different browsers in parallel in different platforms and devices. Due to parallel testing, execution time reduces which results in a faster time to delivery.
  3. Test on Real Devices: To check how the web application looks to an end user it is important to test it under real user conditions, which is why testing on real desktop and mobile devices help get more accurate test results. 
  4. Take Screenshots and Video Logs: For better debugging and reproducing any failed test case, it is a good idea to get rich artifacts like Selenium Logs, Screenshots and Video Logs which you get with BrowserStack Automate.

Why run Selenium ChromeDriver Tests on Real Devices?

BrowserStack Automate enhances Selenium ChromeDriver testing efficiency by providing access to a wide array of real browsers and devices, allowing for comprehensive cross-browser and cross-device testing.

Here are the reasons why you should choose BrowserStack Automate to run your Selenium Tests on Real Devices and Browsers:

  • Parallel Testing: BrowsersStack’s Automate product supports parallel testing by which one can easily test their app on a pool of combinations of device and browser types. This ultimately helps in reducing the execution time taken to run on different platforms and devices and therefore giving quick feedback of the application’s performance.
  • Real Devices and Browsers: It is always wiser to test the application on real devices and browsers to simulate a real user experience. Testing on real devices gives the actual confidence about the application performance. Functional testing and even non-functional testing such performance, load and security should be performed on real devices as testing on emulators may not give accurate results. With Automate one can test on any latest mobile device or web browser without the overhead of purchasing a physical device.
  • Dedicated Dashboard: Running Selenium testcases on Automate product, creates a report in a dashboard which can be referred to manage and monitor the automation testing activities. The dashboard provides an overview of the testing status as Pass/Fail/Pending with all the environment details such as device name, OS version, Platform, browser name, browser version, test execution time and duration, screenshots, etc. It also maintains a history of test executions.
  • Custom Reports with Artifacts: In Automate, custom reports can be generated to provide detailed and customized reports for the automated test execution. With this feature it allows to customize the structure and content of the report as per user’s need. It can include a vast range of test data such as test execution status, device and browser configurations, test duration, video recording, screenshots, etc.
  • Easy Integration with CI/CD Pipeline: BrowserStack’s Automate product can be seamlessly integrated with popular CI/CD tools such as Jenkins, TeamCity, TravisCI. With CI/CD in place, team can achieve faster delivery cycles with great confidence in the reliability, performance and compatibility of the application across different devices and platforms.

Conclusion

Although it’s vital to test web-apps for Chrome, it’s also important for a web app to be optimized for other browsers like Firefox, Safari, Edge, etc. Teams can leverage  BrowserStack, which enable QAs to perform cross browser testing for their web apps across thousand of real browsers and browser versions like Safari, Opera, Edge, etc. All real browsers are installed on real desktop and mobile devices, thus providing the optimal environment for software testing in real user conditions.

Try BrowserStack Now

Tags
Selenium Selenium Webdriver

Featured Articles

Chrome vs Chromium: Core Differences

Exception Handling in Selenium WebDriver

Selenium Testing on Real Chrome Browsers

Run Selenium Tests under real browsers & devices for accurate results