Is there any way to load an extension in chrome browser using Selenium Webdriver?

SeleniumAutomation TestingTesting Tools

We can load an extension in Chrome browser using Selenium webdriver.

While we are using the Chrome browser in our local system, we can add multiple extensions to it.

However, while Chrome browser is launched by Selenium webdriver, those extensions which are available to our local browser may not be present. We have to explicitly add them with the help of the .crx file of the extensions.

To add an extension for example, Momentum, navigate to the below link − https://chrome.google.com/webstore/category/extensions.

Type Momentum in the search box and hit Enter. Select the correct option from the search results.

As the next page is navigated, we shall get the details of this extension. We need to copy the URL of this page.

Visit the link − https://chrome-extension-downloader.com/

Paste the URL we have copied(in the earlier step) on the edit box to the left of the Download Extension button. Then click on Download Extension.

A .crx file(of the Momentum extension) should get downloaded in the system. Now, to add this extension to the Chrome browser launched by Selenium we have to use the ChromeOptions class and create an instance of it.

Then we have to apply the addExtensions method on it. The path of the .crx file that we have downloaded is to be passed as a parameter to this method. Finally, we have to use the DesiredCapabilities class and configure the Chrome browser capability with the setCapability method.

Example

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.io.File;
public class ChromBrwExt{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      //ChromeOptions object
      ChromeOptions o= new ChromeOptions();
      //configure path of .crx file
      o.addExtensions
      (new File("C:\\Users\\Ext\\Momentum_v0.92.2.crx"));
      //DesiredCapabilities object
      DesiredCapabilities cp = DesiredCapabilities.chrome();
      // set browser capability
      cp.setCapability(ChromeOptions.CAPABILITY, o);
      // add capability to driver
      WebDriver driver = new ChromeDriver(cp);
      //URL launch
      driver.get("https://www.google.com/");
      //browser close
      driver.close();
   }
}
raja
Published on 08-Apr-2021 07:30:52
Advertisements