Load chrome extension using selenium
Asked Answered
M

8

38

While running selenium, I need to load a chrome extension from the web store. In my research, I only found how to load an extension from the local machine.

Is it possible for selenium to load an extension from the Web Store?

Mental answered 11/12, 2015 at 11:23 Comment(4)
An option is to use java to download crx file from webstore everytime you run the test scripts and then load the downloaded script into chromeoptions. There are many options to download file from internet in Java. Will the approach acceptable in your case?Supersensible
yes, even downloading the extension from store and then installing it will also do. But I am not sure if we can download CRX file ? Do we have download URLs available ?Mental
yes, it is possible using selenium. refer this Installing extensions via ChromeDriver in seleniumBhang
I don't see any of the proposed solutions offering a way to do this without human interaction upfront - i.e. manually loading the crx file. All but mine that is - mine offers the ability to download the crx file programmatically. we're not talking about using load-extension or add.argument options before starting chrome. nuff said.Yann
F
34

I did this with Python in case anyone was looking.

All you have to do is download the .crx file (I used https://chrome-extension-downloader.com/) and save it somewhere that Python can access it. In my example, I imported it to the same folder as my Python script, to load exampleOfExtensionDownloadedToFolder.crx.

from selenium import webdriver 
from selenium.webdriver.chrome.options import Options 

options = webdriver.ChromeOptions()
options.add_extension('./exampleOfExtensionDownloadedToFolder.crx')
driver = webdriver.Chrome(options=options) 
driver.get('http://www.google.com')
Forjudge answered 20/9, 2018 at 8:17 Comment(4)
Anyone getting the CRX verification failed, this post helped https://mcmap.net/q/66900/-webdriverexception-message-unknown-error-cannot-process-extension-1-from-unknown-error-crx-verification-failed-3Callant
this also works with a zip of a custom packed extensionHorsewoman
"CRX verification failed to parse extension header. Chrome supports only CRX3 format. Does the extension need to be updated?"Colorblind
Make sure you use options = Options() instead of options = webdriver.ChromeOptions()Britanybritches
S
27

I am not sure why you are particular about downloading from Webstore and then install into Chrome.

I found some steps to download chrome extensions:

-With a computer connected to the internet, install the extension from the extension page: https://chrome.google.com/webstore/detail/
-Navigate to the extension source code. In XP this is found at: C:\Documents and Settings\\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions\
-You should see a version folder (ie. "0.0.21_0"). Copy this folder and move it on the machine you want to install on.
-Open up chrome on the disconnected machine and go to Wrench -> Tools -> Extensions
-Click the + next to Developer mode to display the developer options
-Click 'Pack extension...' and choose the version folder as the root directory. Leave the private key file blank. This will create a .crx file in the version folder along with a private key as if you were the developer.

--Or--

1- Find the ID of the extension you’re interested in. When on the details page of the extension, it will be something like : bfbmjmiodbnnpllbbbfblcplfjjepjdn after https://chrome.google.com/webstore/detail/

2- Paste this into any other browser (not Chrome): https://clients2.google.com/service/update2/crx?response=redirect&x=id%3D~~~~%26uc

3- and replacing ~~~~ with the extension ID. You’ll be prompted to save a CRX file. Drag this file to a Chrome window and proceed with installation.

Source: https://productforums.google.com/forum/#!topic/chrome/g02KlhK12fU

Finally, use the downloaded .crx file in ChromeOptions to load the extension

ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);

Source: https://sites.google.com/a/chromium.org/chromedriver/extensions

Supersensible answered 11/12, 2015 at 12:1 Comment(4)
I did this using a JS which return me a download URL for given ID. My final goal is to intercept requests coming out of diff extensions. For this I am using another extension of mine where I am using 'chrome.webRequest.onBeforeRequest' API to capture request. But it seems chrome does not forward requests comming out of extensions to my handler. Another API which I can use is 'chrome.devtools.network.onRequestFinished' but it only works when developer tool is opened. Now I am stuck how to open developer tool using Selenium? Can you plz commnet how I can track requests from different extensions?Mental
not really conversant with chrome extension development. refer to this post #23825871 about modifying extension to include user desired actions in javascript. not sure if it will be helpfulSupersensible
Coming back in 2017, it seems that the link method no longer works. Can anyone confirm?Spacesuit
@Spacesuit see stackoverflow.com/a/14099762 for an updated methodReynaldoreynard
H
14

Here is how to load a chrome extension into chrome Selenium Python

Date = 20-12-19
Chrome version = 79.0.3945.88

The new version of Chrome support crx.crx (crx3) and if you use crx it will throw an error.
If you are using chrome version 73 or above then only follow this step


1> Crate a crx3 file.

1. Go to Chrome web store and search you Extension, copy the link of the extension. Screen shot
2. Go to this site and paste the link and download crx file for your Chrome extension.
3. Go to this GitHub page and download the module which will convert your crx file to crx3 or crx.crx.
4. Now you have your crx.crx or (crx3) file


**2> Python Code to Add chrome extension in selenium**

1. Put your extension.crx.crx file in the same folder as your code or give the path
2. You can copy-paste this code and just change the file crx.crx name at `chrome_options.add_extension(' YOUR - EXTENSION - NAME ')`
import os
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    
    executable_path = "/webdrivers"
    os.environ["webdriver.chrome.driver"] = executable_path
    
    chrome_options = Options()

    chrome_options.add_extension('  YOUR - EXTIONTION  - NAME    ')
    
    driver = webdriver.Chrome(chrome_options=chrome_options)
    driver.get("http://stackoverflow.com")
Hygienic answered 20/12, 2019 at 15:29 Comment(4)
This is a great answer and should be the accepted one in 2020. Thanks a bunch!Ossifrage
@Khan Saad could you help point me to any blog posts or documentation that explains how to execute the extensions after they're successfully added to the driver?Campbellite
The Github don't convert crx in crx3, it convert folder in cr3 Need more explanation pleaseLouisalouisburg
But at the end it does the job so does it matter?Hygienic
P
7
  1. Put chromedriver exe in your document file if you want to follow this and have a successful result.

  2. Download "GET CRX" extension from Google.

  3. Download your extension (i.e. mine is "DHS" for Rest API testing).

  4. Go to Chrome Web Store >> search for your extension (the one you've already downloaded) >> right click on it and click :: GET CRX
    (This should download the CRX file. For my case the CRX file is "extension_1_2_5.crx")

  5. Drop the CRX file in any Chrome window (this can reject it but no worries).

  6. Now, build your test and execute

    public static void openChromeExtension(){
    
        System.setProperty("webdriver.chrome.driver", "/Users/[your local name]/Documents/chromedriver");
    
        ChromeOptions options = new ChromeOptions();
        options.addExtensions(new File("/Users/[your local name]/Documents/extension_1_2_5.crx"));
    
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        ChromeDriver driver = new ChromeDriver(capabilities);
        System.out.println("Opening extension");
        driver.get("chrome-extension://**aejoelaoggembcahagimdiliamlcdmfm**/dhc.html"); 
    
        driver.navigate().refresh();
        System.out.println("Refresh successfully");
    }
    

    //this is the extension URL or you can get the id on chrome://extensions/ find the extension and copy the ID. However, the URL must be the extension URL.

Putrescent answered 17/3, 2016 at 0:35 Comment(2)
The file it's giving me is a .bin file not a .crx file. Is this normal?Bactria
"CRX verification failed to parse extension header. Chrome supports only CRX3 format. Does the extension need to be updated?"Colorblind
A
3

Not sure why, but somebody deleted their answer, which was correct. Here is the content (sourced from @parishodak):

ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);

This particular example is in Java

Anguished answered 11/12, 2015 at 13:46 Comment(1)
I loaded chrome extension - Google Tag Assistant in Selenium WD java by using above code. How to open/observe Tag Assistant panel?Nailbiting
M
1

The above solutions although technically sound not always work as intended, so I thought another way to do it. Because many times I need a lot of things that are better done manually, authentications, certain cookies, etc

I use folders as profiles, I run:

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")

Then I manually install the Extensions and do the logins I need now every-time I start the Webdriver with that folder everything is there

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") #Now you can see the Extensions and the logins done are present

The advantage is you can use multiple folders with different setting and Extensions without the need to install and uninstall Extensions, change settings, change logins etc

Maseru answered 1/2, 2018 at 13:57 Comment(4)
it seems this is not working anymoreBacitracin
@Bacitracin have you tried from selenium.webdriver.chrome.options import OptionsMaseru
@Bacitracin you need to add the extensions manually in between those instancesMaseru
yes, I already used to ChromeOptions to add extension Zip files but its still not workingBacitracin
A
0
using System.IO;
using System.IO.Compression;



  public static class ChromeExtension
        {
            public static string Execute()
            {
                var ParentPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent;
                var DirectoryPath = ParentPath.FullName.Remove(ParentPath.FullName.IndexOf(ParentPath.Name));

                string startPath = $"{DirectoryPath}\\Exchanger\\ChromeExtension";
                string zipPath = $"{DirectoryPath}Exchanger\\Extension.zip";

                if (System.IO.File.Exists(zipPath))
                {
                    System.IO.File.Delete(startPath);
                }

                ZipFile.CreateFromDirectory(startPath, zipPath);


                if (System.IO.File.Exists($"{DirectoryPath}\\Exchanger\\Extension.crx"))
                {
                    System.IO.File.Delete($"{DirectoryPath}\\Exchanger\\Extension.crx");
                }

                System.IO.File.Move(zipPath, $"{DirectoryPath}\\Exchanger\\Extension.crx");

                return $"{DirectoryPath}\\Exchanger\\Extension.crx";
            }

        }

....////....

Used: 
var options = new ChromeOptions();   
options.AddExtension(ChromeExtension.Execute());

....////....
Actinometer answered 10/9, 2017 at 13:29 Comment(0)
A
0

To add any chrome extension using selenuim and Java I tried many ways but the following thing worked for me. By using the we can add any chrome extension/plugin and launch it also through script.

Step1: Open chrome https://chrome.google.com/webstore/category/extensions driver.get("https://chrome.google.com/webstore/category/extensions");

Search for your required extension in search box(Google Translate). And click required on from autosuggestion list. Then click on extension heading. Then it will open extension details page.

Step2: Without use step1 one also we can open this extension page directly by plugin id. Directly open the following link is same.
Ex:https://chrome.google.com/webstore/detail/google-translate/aapbdbdomjkkjkaonfhkkikfgjllcleb driver.get("https://chrome.google.com/webstore/detail/google-translate/aapbdbdomjkkjkaonfhkkikfgjllcleb");

Now click on Add to Chrome, handle popup using Robot keys like TAB & EN

        Robot rb=new Robot();
        rb.keyPress(KeyEvent.VK_TAB);
        Thread.sleep(300);
        rb.keyRelease(KeyEvent.VK_TAB);
        Thread.sleep(1000);
        rb.keyPress(KeyEvent.VK_ENTER);
        Thread.sleep(300);
        rb.keyRelease(KeyEvent.VK_ENTER);

Now successfully added chrome extension to chrome browser. To launch chrome extension create a shortcut for this installed extension and using that shortcut key to open extension when you want to launch/open

driver.get("chrome://extensions/shortcuts");

click on shortcut icon and press shortcut key ex: Control+Q. Use the robot keys for this. Once you added this shortcut key by pressing this key you can launch extension.

Amar answered 7/10, 2023 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.