How to disable 'This type of file can harm your computer' pop up - selenium

I'm using selenium chromedriver for automating web application.
In my application, I need to download xml files. But when I download xml file, I get 'This type of file can harm your computer' pop up. I want to disable this pop up using selenium chromedriver and I want these type of files to be downloaded always. How can this be done?
Selenium version : 2.47.1
Chromedriver version : 2.19
UPDATE it's long standing Chrome bug from 2012.

The problem with XML files started to happen to me as of Chrome 47.0.2526.80 m.
After spending maybe 6 hours trying to turn off every possible security option I tried a different approach.
Ironically, it seems that turning on the Chrome option "Protect you and your device from dangerous sites" removes the message "This type of file can harm your computer. Do you want to keep file.xml anyway?"
I am using 'Ruby' with 'Watir-Webdriver' where the code looks like this:
prefs = {
'safebrowsing' => {
'enabled' => true,
}
}
b = Watir::Browser.new :chrome, :prefs => prefs
Starting the browser like this, with safebrowsing option enabled, downloads the xml files without the message warning. The principle should be the same for Selenium with any programming language.
#####
Edited: 13-04-2017
In latest version of Google Chrome the above solution is not enough. Additionally, it is necessary to start the browser with the following switch:
--safebrowsing-disable-download-protection
Now, the code for starting the browser would look something like this:
b = Watir::Browser.new :chrome, :prefs => prefs, :switches => %w[--safebrowsing-disable-download-protection]))

I am posting below the complete code that got file download working for me:
Hope it helps :-) I am using Java-Selenium
System.setProperty("webdriver.chrome.driver", "C:/chromedriver/chromedriver.exe");
String downloadFilepath = "D:/MyDeskDownload";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
chromePrefs.put("safebrowsing.enabled", "true");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(cap);

Following Python code works for me
chromeOptions = webdriver.ChromeOptions()
prefs = {'safebrowsing.enabled': 'false'}
chromeOptions.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=chromeOptions)

The accepted answer stopped working after a recent update of Chrome. Now you need to use the --safebrowsing-disable-extension-blacklist and --safebrowsing-disable-download-protection command-line switches. This is the WebdriverIO config that works for me:
var driver = require('webdriverio');
var client = driver.remote({
desiredCapabilities: {
browserName: 'chrome',
chromeOptions: {
args: [
'disable-extensions',
'safebrowsing-disable-extension-blacklist',
'safebrowsing-disable-download-protection'
],
prefs: {
'safebrowsing.enabled': true
}
}
}
});
Note that I am also disabling extensions, because they generally interfere with automated testing, but this is not strictly needed to fix the problem with downloading XML and JavaScript files.
I found these switches by reading through this list. You can also see them in the Chromium source.

I came across this recently, using Katalon Studio, Chrome version 88.
Thankfully just the enabling safebrowsing did the trick. You access the settings via "Project Settings" and you navigate to "Desired Capabilities" -> "Web UI" -> "Chrome".
If you don't have a "prefs" setting add it and set the type to Dictionary. Then in the Value add a boolean named "safebrowsing.enabled" and set the value to "true".
Result might look like:
(And you can the default directory setting has nothing to do with this example).

I used all of suggested chrome options in C# and only when my internet connected worked for me but when internet disconnected none of them work for me.
(I'm not sure.may be chrome safebrowsing need to internet connection)
By using older version of chrome(version71) and chromedriver(version 2.46) and after downloading,i saw downloaded XML file name constains 'Unconfirmed' with 'crdownload' extension
and parsing XML file wouldn't work properly.
Finally, creating wait with Thread.Sleep(1000) solved my problem.
IWebDriver Driver;
//chromedriver.exe version2.46 path
string path = #"C:\cd71";
ChromeDriverService driverService = ChromeDriverService.CreateDefaultService(path, "chromedriver.exe");
ChromeOptions options = new ChromeOptions();
// options.AddArgument("headless");
options.AddArgument("--window-position=-32000,-32000");
options.AddUserProfilePreference("download.default_directory", #"c:\xmlFiles");
options.AddUserProfilePreference("download.prompt_for_download", false);
options.AddUserProfilePreference("disable-popup-blocking", "true");
options.AddUserProfilePreference("safebrowsing.enabled", "true");
Driver = new ChromeDriver(driverService, options);
try
{
Driver.Navigate().GoToUrl(url);
Thread.Sleep(1000);
//other works like: XML parse
}
catch
{
}

For context, I had a .csv with a list of .swf flash documents and their respective urls. Since the files could only be accessed after a valid login, I couldn't use a simple requests based solution.
Just like .xml, downloading a .swf triggers a similar prompt.
None of the answers worked for me.
So I stripped away all the extra arguments and settings the above answers proposed and just made the chrome instance headless.
options.add_argument("--headless")
prefs = {
"download.default_directory": "C:\LOL\Flash",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
}
options.add_experimental_option("prefs",prefs)

The only workaround that works for me:
Use argument with path to chrome profile
chromeOptions.add_argument(chrome_profile_path)
Search for file download_file_types.pb in chrome profile folder.
In my case ..chromedriver\my_profile\FileTypePolicies\36\download_file_types.pb
Backup this file and then open with any hexeditor (you can use oline).
Search for the filetype you want to download, i.e. xml and change it to anything i.e. xxx

Im using Google Version 80.0.3987.122 (Official Build) (32-bit) and ChromeDriver 80.0.3987.106. Getting the same error even after adding the below while downloading a .xml file.
$ChromeOptions = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$ChromeOptions.AddArguments(#(
"--disable-extensions",
"--ignore-certificate-errors"))
$download = "C:\temp\download"
$ChromeOptions.AddUserProfilePreference("safebrowsing.enabled", "true");
$ChromeOptions.AddUserProfilePreference("download.default_directory", $download);
$ChromeOptions.AddUserProfilePreference("download.prompt_for_download", "false");
$ChromeOptions.AddUserProfilePreference("download.directory_upgrade", "true");
$ChromeDriver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($chromeOptions)

Related

How to get Chrome Dev Tools logs with Selenium C#?

My aim is getting the transfer size of page. Explained below image.
How can I get it with C# code using selenium NuGet package? I searched chrome dev tools.
https://chromedevtools.github.io/devtools-protocol/tot/Network/
I see there is Network.dataReceived property. As I understand I need to get this.
My code
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium;
ChromeOptions options = new ChromeOptions();
//Following Logging preference helps in enabling the performance logs
options.SetLoggingPreference("performance", LogLevel.All);
//Based on your need you can change the following options
options.AddUserProfilePreference("intl.accept_languages", "en-US");
options.AddUserProfilePreference("disable-popup-blocking", "true");
options.AddArgument("test-type");
options.AddArgument("--disable-gpu");
options.AddArgument("no-sandbox");
options.AddArgument("start-maximized");
options.LeaveBrowserRunning = true;
//Creating Chrome driver instance
IWebDriver driver = new ChromeDriver(options);
var url = " https://...............";
driver.Navigate().GoToUrl(url);
//Extracting the performance logs
var logs = driver.Manage().Logs.GetLog("performance");
for (int i = 0; i < logs.Count; i++)
{
Console.WriteLine((i+1) + " - " + logs[i].Message);
}
I found some code that possibly worked in old versions. I am using Chrome 105 version(as a nuget package, and selenium web dirver 4.0.0) and Chrome should be 105 version. In C# I can not find the below code, this is Java version:
for (LogEntry entry : driver.manage().logs().get(LogType.PERFORMANCE)) {
if(entry.getMessage().contains("Network.dataReceived")) {
Matcher dataLengthMatcher = Pattern.compile("encodedDataLength\":(.*?),").matcher(entry.getMessage());
dataLengthMatcher.find();
}
Even if we can do this with C# code, I dont believe driver.Manage().Logs.GetLog("performance") returns the same with the listed lines in dev tools network section. Is there nay option about that?

Download file through Google Chrome RemoteWebDriver- headless mode in Linux using Selenium Java [duplicate]

I'm do me code in Cromedrive in 'normal' mode and works fine. When I change to headless mode it don't download the file. I already try the code I found alround internet, but didn't work.
chrome_options = Options()
chrome_options.add_argument("--headless")
self.driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=r'{}/chromedriver'.format(os.getcwd()))
self.driver.set_window_size(1024, 768)
self.driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': os.getcwd()}}
self.driver.execute("send_command", params)
Anyone have any idea about how solve this problem?
PS: I don't need to use Chomedrive necessarily. If it works in another drive it's fine for me.
First the solution
Minimum Prerequisites:
Selenium client version: Selenium v3.141.59
Chrome version: Chrome v77.0
ChromeDriver version: ChromeDriver v77.0
To download the file clicking on the element with text as Download Data within this website you can use the following solution:
Code Block:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless")
options.add_argument("--window-size=1920,1080")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe', service_args=["--log-path=./Logs/DubiousDan.log"])
print ("Headless Chrome Initialized")
params = {'behavior': 'allow', 'downloadPath': r'C:\Users\Debanjan.B\Downloads'}
driver.execute_cdp_cmd('Page.setDownloadBehavior', params)
driver.get("https://www.mockaroo.com/")
driver.execute_script("scroll(0, 250)");
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#download"))).click()
print ("Download button clicked")
#driver.quit()
Console Output:
Headless Chrome Initialized
Download button clicked
File Downloading snapshot:
Details
Downloading files through Headless Chromium was one of the most sought functionality since Headless Chrome was introduced.
Since then there were different work-arounds published by different contributors and some of them are:
Downloading with chrome headless and selenium
Python equivalent of a given wget command
Now the, the good news is Chromium team have officially announced the arrival of the functionality Downloading file through Headless Chromium.
In the discussion Headless mode doesn't save file downloads #eseckler mentioned:
Downloads in headless work a little differently. There's the Page.setDownloadBehavior devtools command to set a download folder. We're working on a way to use DevTools network interception to stream the downloaded file via DevTools as well.
A detailed discussion can be found at Issue 696481: Headless mode doesn't save file downloads
Finally, #bugdroid revision seems to have nailed the issue for us.
[ChromeDriver] Added support for headless mode to download files
Previously, Chromedriver running in headless mode would not properly download files due to the fact it sparsely parses the preference file given to it. Engineers from the headless chrome team recommended using DevTools's "Page.setDownloadBehavior" to fix this. This changelist implements this fix. Downloaded files default to the current directory and can be set using download_dir when instantiating a chromedriver instance. Also added tests to ensure proper download functionality.
Here is the revision and commit
From ChromeDriver v77.0.3865.40 (2019-08-20) release notes:
Resolved issue 2454: Headless mode doesn't save file downloads [Pri-2]
Solution
Update ChromeDriver to latest ChromeDriver v77.0 level.
Update Chrome to Chrome Version 77.0 level. (as per ChromeDriver v76.0 release notes)
Note: Chrome v77.0 is yet to be GAed/pushed for release so till then you can download and install a development build and test either from:
Chrome Canary
Latest build from the Dev Channel
Outro
However Mac OSX users have a wait for their pie as On Chromedriver, headless chrome crashes after sending Page.setDownloadBehavior on MacOSX.
Chomedriver Version: 95.0.4638.54
Chrome Version 95.0.4638.69
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless")
options.add_argument("--start-maximized")
options.add_argument("--no-sandbox")
options.add_argument("--disable-extensions")
options.add_argument('--disable-dev-shm-usage')
options.add_argument("--disable-gpu")
options.add_argument('--disable-software-rasterizer')
options.add_argument("user-agent=Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166")
options.add_argument("--disable-notifications")
options.add_experimental_option("prefs", {
"download.default_directory": "C:\\link\\to\\folder",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing_for_trusted_sources_enabled": False,
"safebrowsing.enabled": False
}
)
What seemed to work was that I used "\\" instead of "/" for the address. The latter approach didn't throw any error, but didn't download any documents either. But, using double back slashes did the job.
For javascript use below code:
const chrome = require('selenium-webdriver/chrome');
let options = new chrome.Options();
options.addArguments('--headless --window-size=1500,1200');
options.setUserPreferences({ 'plugins.always_open_pdf_externally': true,
"profile.default_content_settings.popups": 0,
"download.default_directory": Download_File_Path });
driver = await new webdriver.Builder().setChromeOptions(options).forBrowser('chrome').build();
Then switch tabs as soon as you click the download button:
await driver.sleep(1000);
var Handle = await driver.getAllWindowHandles();
await driver.switchTo().window(Handle[1]);
This C# works for me
Note the new headless option https://www.selenium.dev/blog/2023/headless-is-going-away/
private IWebDriver StartBrowserChromeHeadlessDriver()
{
var chromeOptions = new ChromeOptions();
chromeOptions.AddArgument("--headless=new");
chromeOptions.AddArgument("--window-size=1920,1080");
chromeOptions.AddUserProfilePreference("download.default_directory", downloadFolder);
var chromeDownload = new Dictionary<string, object>
{
{ "behavior", "allow" },
{ "downloadPath", downloadFolder }
};
var driver = new ChromeDriver(driverFolder, chromeOptions, TimeSpan.FromSeconds(timeoutSecs));
driver.ExecuteCdpCommand("Browser.setDownloadBehavior", chromeDownload);
return driver;
}
import pathlib
from selenium.webdriver import Chrome
driver = Chrome()
driver.execute_cdp_cmd("Page.setDownloadBehavior", {
"behavior": "allow",
"downloadPath": str(pathlib.Path.home().joinpath("Downloads"))
})
I don't think you should be using the browser for downloading content, leave it to Chrome developers/testers.
I believe you should rather get href attribute of the element you want to download and obtain it using requests library
If your site requires authentication you could fetch cookies from the browser instance and pass them to requests.Session.

How to remove the infobar "Microsoft Edge is being controlled by automated test software" in selenium test

We are using selenium to run test against "Chromium based Edge".
"The Chromium Edge" is downloaded from https://www.microsoftedgeinsider.com/en-us/download and the version is 80.0.334.2 (Official build) dev (64-bit).
We got the matched driver msedgedriver.exe from https://msedgewebdriverstorage.z22.web.core.windows.net/
We add the "C:\Program Files (x86)\Microsoft\Edge Dev\Application" to the environment "PATH" so that the executable "msedge.exe" will be found during the test.
After starting the selenium server with option -Dwebdriver.edge.driver="pathTo\msedgedriver.exe", we can get the test run in the "Chromium Edge" as below:
But there is a infobar "Microsoft Edge is being controlled by automated test software", just like we run test with chrome browser. With chrome, we can remove that infobar by setting the following ExperimentalOption to ChromeOptions
useAutomationExtension=false
excludeSwitches=[enable-automation]
prefs={credentials_enable_service=false, profile={password_manager_enabled=false}}
I tried to set the same options and I got a browser launched without the infobar, but it is a chrome browser NOT the "Chromium Edge".
You could refer to the following code (C# code) to set the chrome options and remove the infobar.
var edgechromiumService = ChromeDriverService.CreateDefaultService(#"E:\edgedriver_win64", "msedgedriver.exe");
// user need to pass the driver path here....
ChromeOptions edgechromeOptions = new ChromeOptions
{
BinaryLocation = #"C:\Program Files (x86)\Microsoft\Edge Dev\Application\msedge.exe",
};
edgechromeOptions.AddAdditionalCapability("useAutomationExtension", false);
edgechromeOptions.AddExcludedArgument("enable-automation");
using (IWebDriver driver = new ChromeDriver(edgechromiumService, edgechromeOptions))
{
driver.Navigate().GoToUrl("https://www.bing.com/");
Console.WriteLine(driver.Title.ToString());
//driver.Close();
Console.ReadKey();
}
The result like this:
For Java applications, please try to use the following code:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeOptions;
import java.util.*;
public class Edgeauto {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "your\\path\\to\\edge\\webdriver\\msedgedriver.exe");
ChromeOptionschromeOptions = new ChromeOptions();
chromeOptions.setBinary("C:\\Program Files (x86)\\Microsoft\\Edge Dev\\Application\\msedge.exe");
chromeOptions.setExperimentalOption("useAutomationExtension", false);
chromeOptions.setExperimentalOption("excludeSwitches",Collections.singletonList("enable-automation"));
EdgeOptions edgeOptions = new EdgeOptions().merge(chromeOptions);
WebDriver driver = new ChromeDriver(edgeOptions);
driver.get("https://www.google.com/");
}
}
I think that I can explain the all the confusions (perhaps for myself 😊). In the following link Microsoft Chromium Edge
We can find something as below:
If you were previously automating or testing Microsoft Edge (Chromium) by using ChromeDriver and ChromeOptions, your WebDriver code will not run successfully against Microsoft Edge 80 or later. This is a breaking change and Microsoft Edge (Chromium) no longer accepts these commands. You must change your tests to use EdgeOptions and Microsoft Edge Driver.
So we can handle the Chromium-Edge (version is smaller than 80) completely as a chrome browser.
System.setProperty("webdriver.chrome.driver", "C:\\SeleniumPlus\\extra\\msedgedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary("C:\\Program Files (x86)\\Microsoft\\Edge Dev\\Application\\msedge.exe");
chromeOptions.setExperimentalOption("useAutomationExtension", false);
chromeOptions.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
ChromeDriver driver = new ChromeDriver(chromeOptions);
driver.get("http://www.google.com");
driver.close();
For the Chromium-Edge (version 80 or later), we should treat it as an Edge browser, the code is as below:
The problem is that EdgeOptions does NOT provide enough APIs (setBinary, setExperimentalOption) as ChromeOptions ☹.
I checked the selenium’s source code at github and I found that the EdgeOptions has already supported those methods as ChromeOptions. So I downloaded the latest official build whose version is 3.141.59, and it was released this on Dec 20, 2018 and I found out that it doesn’t contain the latest source code ☹.
So I got the alpha release 4.0.0-alpha-4 and it does contain the latest source code.
System.setProperty("webdriver.edge.driver", "C:\\SeleniumPlus\\extra\\msedgedriver.exe");
EdgeOptions edgeOptions = new EdgeOptions();
edgeOptions.setBinary("C:\\Program Files (x86)\\Microsoft\\Edge Dev\\Application\\msedge.exe");
edgeOptions.setExperimentalOption("useAutomationExtension", false);
edgeOptions.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
EdgeDriver driver = new EdgeDriver(edgeOptions);
driver.get("http://www.google.com");
driver.close();
Finally I want to thank my comrade comrade Carl, he helped me find the trick.
You saw it right.
As per the article Microsoft’s Edge Chromium browser will launch on January 15th with a new logo Microsoft is planning to release its Edge Chromium browser on January 15th 2020 with availability for Windows 10, Windows 7, Windows 8, and macOS. This came just after Microsoft released the beta version of Edge.
Now, this Beta also means that Microsoft is edging closer to the release stage for its Chromium browser. Microsoft first released its Canary and Developer builds of Edge back in April, and the company has spent the past four months working alongside Google to improve Chromium for Windows. That work also involved Microsoft getting used to the cadence of delivering a Chromium browser.
Hence adding the ExperimentalOption you see the Microsoft’s Edge Chromium browser almost like a Chromium / Chrome browser.
#Zhi Lv - MSFT
What is the browser you are launching? Chrome or Chromium-Edge? I am using selenium java code, if I run the similar java code as below, it will fail with error
The path to the driver executable must be set by the webdriver.chrome.driver system property;
System.setProperty("webdriver.edge.driver", "C:\\SeleniumPlus\\extra\\msedgedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary("C:\\Program Files (x86)\\Microsoft\\Edge Dev\\Application\\msedge.exe");
chromeOptions.setExperimentalOption("useAutomationExtension", false);
chromeOptions.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("http://www.google.com");
If I create an edge capabilities and merge the ChromeOption into it, I can see that "Chromium-Edge" gets started without the "infobar", but it just gets stuck there and fails with an error
unknown error: unrecognized Chrome version: Edg/80.0.361.5
System.setProperty("webdriver.edge.driver", "C:\\SeleniumPlus\\extra\\msedgedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary("C:\\Program Files (x86)\\Microsoft\\Edge Dev\\Application\\msedge.exe");
chromeOptions.setExperimentalOption("useAutomationExtension", false);
chromeOptions.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
DesiredCapabilities m_capability = DesiredCapabilities.edge();
m_capability.merge(chromeOptions);
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), m_capability);
driver.get("http://www.google.com");
From the "selenium server" console, I can see, the "browserName" is "chrome", I guess that is the reason why chrome's options is working to get rid of the "infobar"
15:37:55.502 INFO [ActiveSessionFactory.apply] - Capabilities are: {
"browserName": "chrome",
"goog:chromeOptions": {
"args": [
],
"binary": "C:\\Program Files (x86)\\Microsoft\\Edge Dev\\Application\\msedge.exe",
"excludeSwitches": [
"enable-automation"
],
"extensions": [
],
"useAutomationExtension": false
},
"platform": "WINDOWS",
"version": ""
}
If I set the "browserName" to "MicrosoftEdge" after merging the chrome's options as below, it can get the "Chromium-Edge" started, but the chrome's options do not work any more, which means the "infobar" is still there.
m_capability.merge(chromeOptions);
m_capability.setCapability(CapabilityType.BROWSER_NAME, BrowserType.EDGE);

Enable clipboard in automated tests with Protractor and webdriver

I want to test with Protractor an Angular application that accesses the system clipboard using the clipboard api. The problem is that, when executing the test, the Chromium browser asks the user for permission to access the clipboard. I can't close this box from the test, because this is not a DOM element nor an alert window, and it seems not to be any way to access it from Protractor.
clipboard permissions
I have tried to automatically give permission in Chrome, in protractor setup. First, I looked for a command line switch that do it, but it seems not to exist.
Then I found a way that apparently works, but I don't know if its stable: to set an "exception" in Chrome user profile, using the Capabilities of the chrome driver of webdriver. Basically, I add the following lines of my protractor config file:
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'prefs': {
'profile.content_settings.exceptions.clipboard': {
'http://localhost:8000,*': {'last_modified': Date.now(), 'setting': 1}
}
}
}
}
I have found the value by looking inside Default/Preferences file inside my Chrome profile.
It now works for me, but I don't want to use undocumented features, since they can change anytime without notice. Do you know a better way of doing this? Thanks.
If anyone is looking to do something similar with C#, I have adapted the code as such:
var options = new ChromeOptions();
var clipboardException = new Dictionary<string, object> {
{"[*.]myurl.com,*",
new Dictionary<string, object> {
{"last_modified", DateTimeOffset.Now.ToUnixTimeMilliseconds()},
{"setting", 1}
}
}
};
options.AddUserProfilePreference("profile.content_settings.exceptions.clipboard", clipboardException);

Unable to install WebExtension with Selenium

I'm trying to test my firefox webextension but firefox refuses to install it because it doesn't have the install.rdf file. But that file is not used anymore by webextensions.
const firefox = require('selenium-webdriver/firefox');
const webdriver = require('selenium-webdriver');
require('geckodriver');
let profile = new firefox.Profile();
profile.addExtension(process.cwd() + '/build/firefox/');
profile.setPreference('extensions.firebug.showChromeErrors', true);
let options = new firefox.Options().setProfile(profile);
let _driver = new webdriver.Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();
Error: ENOENT: no such file or directory, open '/dev/webext/build/firefox/install.rdf'
Is there a setting that I need to enable to tell it it's a webextension?
The WebExtension API is not yet supported by Selenium v3.4.0 . The method Profile::addExtension only works for a legacy addon where install.rdf is present at the root.
To test a web extension, you can either use a profile where the extension is already installed, or you can implement the custom command available with GeckoDriver since v0.17.0:
var webdriver = require('selenium-webdriver');
var Command = require('selenium-webdriver/lib/command').Command;
function installWebExt(driver, extension) {
let cmd = new Command('moz-install-web-ext')
.setParameter('path', path.resolve(extension))
.setParameter('temporary', true);
driver.getExecutor()
.defineCommand(cmd.getName(), 'POST', '/session/:sessionId/moz/addon/install');
return driver.schedule(cmd, 'installWebExt(' + extension + ')');
}
var driver = new webdriver.Builder()
.forBrowser('firefox')
.build();
installWebExt(driver, "C:\\temp\\extension.zip");
This is an issue with FirefoxDriver. This issue is already logged in both SeleniumHQ/selenium#4184 and
mozilla/geckodriver#759
GeckoDriver says that
A workaround for the time being would be to use the add-on endpoints
geckodriver 0.17.0 provides to get an extension installed from the
local disk.
https://github.com/mozilla/geckodriver/blob/release/src/marionette.rs#L66
So you have to use the geckodriver endpoints to do that. I have already mentioned on how to use the endpoints here