Adding extension to Selenium2(WebDriver) chrome driver

血红的双手。 提交于 2019-12-31 01:53:29

问题


I'm using the code below to start chrome using webdriver (selenium 2)

            Map<String, String> mobileEmulation = new HashMap<String, String>();
            mobileEmulation.put("deviceName", "BlackBerry PlayBook");

            Map<String, Object> chromeOptions = new HashMap<String, Object>();
            chromeOptions.put("mobileEmulation", mobileEmulation);
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
            driver = new ChromeDriver(capabilities);

How can I also load a Chrome extension while also keeping the options above?


回答1:


Finally figured it out!

Per the ChromeDriver capabilites page, you need to convert the .crx file into a base-64 encoded string. So the final answer will look something like this:

ArrayList<String> ext = new ArrayList<>();
extensionLocation = extensionDir + sep + extensionName + ".crx";
extension = new File(extensionLocation);
if (extension.exists() && !extension.isDirectory()) {
    ext.add(Data.base64Encoder(extensionLocation));
}
chromeOptions.put("extensions", ext);

Where Data.base64encoder() is my custom method for encoding. There are plenty of examples of how to do that based on the version of Java you're running. Basically send it the location, have it read in the binary, and return a string.




回答2:


Use below code:-

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);

Hope it will help you :)



来源:https://stackoverflow.com/questions/35858679/adding-extension-to-selenium2webdriver-chrome-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!