I'm having issues with running chrome driver in headless mode and interacting with Print Dialog box. It seems that headless chrome doesn't even open Print Dialog Box.
Here is my code for clicking on Save As Pdf button
private static void clickOnSaveAsPdf() {
WebElement saveAsPdfButton = chromeDriver.findElement(By.xpath("//*[#id=\"root\"]/div/div[3]/div[1]/main/div/div/div[1]/div[3]/div/button[2]"));
saveAsPdfButton.click();
}
This part of code above is executed without issues every time. So the issues start when i try to switch windows and focus on print dialog box. When I execute this line of code:
System.out.println(chromeDriver.getWindowHandles());
I get different results when in headless and when in non-headless.
In non-headless mode result I'm getting is: [CDwindow-55CA15B96D8DB58A454CC30B30F0F970, CDwindow-8CB30AB28BC2E8BCDE395BAA9F7B9101]
But in headless mode, result I'm getting is: [CDwindow-15ED0AA78CE73CA53CA71E6FB2A94998]
So, obviously, headless chrome doesn't see print dialog box. Is there any way I can access it? Here is the method that starts ChromeDriver, with its options and prefs:
public static void runChromeDriver() {
String chromeDriverPath = "/home/nemanja/Downloads/chromedriver_linux64/chromedriver";
System.setProperty("webdriver.chrome.driver", chromeDriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--window-size=1920, 1080");
options.addArguments("--ignore-certificate-errors");
HashMap<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_settings.popups", 0);
prefs.put("download.default_directory", getFullPathToTempDirectory());
prefs.put("download.prompt_for_download", false);
prefs.put("download.directory_upgrade", true);
prefs.put("plugins.always_open_pdf_externally", true);
options.setExperimentalOption("prefs", prefs);
chromeDriver = new ChromeDriver(options);
}
Some further info, I'm using Java 17, ChromeDriver v111 and my OS is Ubuntu 22.04.
Before you invoke getWindowHandles() ensure that the second window handle is present inducing WebDriverWait for numberOfWindowsToBe(n) as follows:
new WebDriverWait(driver, Duration.ofSeconds(5)).until(ExpectedConditions.numberOfWindowsToBe(2));
System.out.println(chromeDriver.getWindowHandles());
Related
Based on what I have read, there is a way to do this for Google Chrome versions < 50 and a way to do this for Google Chrome versions > 50. I am using Google Chrome 91.
There is an answer on to this located here: How to click Allow on Show Notifications popup using Selenium Webdriver
which states that I need to do something like this:
//Create a map to store preferences
Map<String, Object> prefs = new HashMap<String, Object>();
//add key and value to map as follow to switch off browser notification
//Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setting_values.notifications", 2);
//Create an instance of ChromeOptions
ChromeOptions options = new ChromeOptions();
// set ExperimentalOption - prefs
options.setExperimentalOption("prefs", prefs);
//Now Pass ChromeOptions instance to ChromeDriver Constructor to initialize chrome driver which will switch off this browser notification on the chrome browser
WebDriver driver = new ChromeDriver(options);
However, this does not work for me. This is what the pop up looks like
and this is how I am using it:
// Create a map to store preferences (to disable pop-up notifications)
Map<String, Object> prefs = new HashMap<String, Object>();
// add key and value to map as follow to switch off browser notification
// Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setting_values.notifications", 2);
// for local automated testing
this.chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("prefs", prefs);
chromeOptions.addArguments("--disable-notifications");
chromeOptions.addArguments("start-maximized");
String chromeDriverPath = "resources/chromedriver-91.exe";
System.setProperty("webdriver.chrome.driver", chromeDriverPath);
this.driver = new ChromeDriver(chromeOptions);
System.out.println("new chrome driver started.....");
this.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
So as you can see, I have tried multiple different ways. "--disable-notifications" did not work and neither did chromeOptions.setExperimentalOption("prefs", prefs);
When I run my program, the pop-up is still there, I need to Selenium to click "Allow" on the pop-up so I can continue with the rest of the program.
You are trying to download a file, which is different behavior than showing notifications. Try
prefs.put("profile.default_content_setting_values.automatic_downloads", 1);
I'm trying to download a file with Selenium Chromedriver through Electron. As we could not handle the popup window with selecting folder to download in, I tried to avoid this popup in this way:
prefs.put("download.prompt_for_download", false);
But it doesn't work. The full code is:
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> prefs = new HashMap<>();
prefs.put("profile.default_content_settings.popups", 0);
prefs.put("download.default_directory", LocationUtil.getDownloadFolderPath());
prefs.put("download.prompt_for_download", false);
prefs.put("safebrowsing.enabled", false); // to disable security check eg. Keep or cancel button
options.setExperimentalOption("prefs", prefs);
ChromeDriver chromeDriver= new ChromeDriver(options);
Also tried to put these prefs through Capabilities but with no success.
((MutableCapabilities) chromeDriver.getCapabilities()).setCapability(ChromeOptions.CAPABILITY, options);
Versions are:
ChromeDriver 80.0.3987.16
Selenium Java 3.141.59
How could I download the file in a specific directory without popup window in an Electron app?
UPD: Tested with browser Chrome - all things are fine.
Seems you were pretty close enough.
Apart from adding the preference of download.prompt_for_download to false you need to set a couple of more preferences as follows:
You need to add the type of file you wish you auto download. As an example to automatically download xml files you need to add:
prefs.put("download.extensions_to_open", "application/xml");
You need to enable/disable safebrowsing.enabled as follows:
prefs.put("safebrowsing.enabled", true);
Now you need to add the argument to safebrowsing-disable-download-protection
options.addArguments("--safebrowsing-disable-download-protection");
Next, you need to add the argument to safebrowsing-disable-extension-blacklist
options.addArguments("safebrowsing-disable-extension-blacklist");
Finally, to click on the element to initiate the download, you need to induce WebDriverWait for the elementToBeClickable().
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("element_xpath"))).click();
Clubbing it up altogether, as a demonstration, to download a xml file from the website your effective code block will be:
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> prefs = new HashMap<>();
prefs.put("profile.default_content_settings.popups", 0);
prefs.put("download.default_directory", LocationUtil.getDownloadFolderPath());
prefs.put("download.prompt_for_download", false);
prefs.put("safebrowsing.enabled", true);
options.setExperimentalOption("prefs", prefs);
ChromeDriver chromeDriver= new ChromeDriver(options);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
options.addArguments("start-maximized");
options.addArguments("--safebrowsing-disable-download-protection");
options.addArguments("safebrowsing-disable-extension-blacklist");
WebDriver driver = new ChromeDriver(options);
driver.get("http://www.landxmlproject.org/file-cabinet");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='MntnRoad.xml']//following::span[1]//a[text()='Download']"))).click();
Browser Snapshot:
References
You can find a couple of relevant reference discussions in:
How to hide the warning “This type of file can harm your computer” while downloading .xml file using Chrome Chromedriver 79 with Selenium Java
How to download XML files avoiding the popup This type of file may harm your computer through ChromeDriver and Chrome using Selenium in Python
While downloading a python script file using selenium webdriver getting a popup which saying "This type of file can harm your computer..." then keep and discard button. i do not want that popup . while clicking on download it should download without the popup. i am running the script in Chrome 75 version.
And tried putting
chromePrefs.put("safebrowsing.enabled", "false");
options.addArguments("--safebrowsing-disable-extension-blacklist");
options.addArguments("--safebrowsing-disable-download-protection");
this while initializing the driver , but nothing worked for me.
//Boilerplate code for setting driver and download path
System.setProperty("webdriver.chrome.driver", "--driver path--");
String path = "Download path";
HashMap<String, Object> prefs = new HashMap<String, Object>();
//setting browser preference values such as popup and download path
chromePrefs.put("profile.managed_default_content_settings.popups", 2);
chromePrefs.put("safebrowsing.enabled", "true");
chromePrefs.put("download.default_directory", path);
//Boilerplate code for setting preferences in chrome options
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(capabilities);
Above code snippet should help you to create a chrome driver, with popups disabled capability.
for this to work on different versions of chrome you might have to play around with
"managed_default_content_settings.popups" or
"profile.default_content_settings.popups"
attributes and its values (0,1 or 2).
Hope this helps !!
I am running my tests in Google Chrome using chromedriver.exe binary. At one particular page this pop up comes which doesn't intervene/effect with the test but client doesn't want to see it. Possible reason could be, at the failure of test case it will capture the screenshot along with this pop up.
How can I create a chrome profile or capabilities which would disable this pop up?
Something like this:
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:/Users/user_name/AppData/Local/Google/Chrome/User Data");
Edit:
This code stopped the "Know your location" pop up to come but generated another pop up. So its only partially working.
options.addArguments("--enable-strict-powerful-feature-restrictions");
driver = new ChromeDriver(options);
Use --disable-geolocation, Chrome Options as given below:
options.addArguments("--disable-geolocation");
Also list of chrome command-line switches can be found in the below link:
http://peter.sh/experiments/chromium-command-line-switches/
Declaring in the following way worked for me.
// Declare variables
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
Map<String, Object> profile = new HashMap<String, Object>();
Map<String, Object> contentSettings = new HashMap<String, Object>();
// Specify the ChromeOption we need to set
contentSettings.put(“geolocation”, 1);
profile.put(“managed_default_content_settings”, contentSettings);
prefs.put(“profile”, profile);
options.setExperimentalOption(“prefs”, prefs);
// Declare the capability for ChromeOptions
caps.setCapability(ChromeOptions.CAPABILITY, options);
This code solved my problem with geolocation
options.AddUserProfilePreference("profile.default_content_setting_values.geolocation", 2);
The --disable-geolocation flag didn't do anything for me.
I am also running with incognito on, so that might be affecting some things.
I can confirm that the following python selenium code will disable the location popup
prefs = {
"profile.default_content_setting_values.geolocation": 2,
}
options.add_experimental_option("prefs", prefs)
In the interest of digging deeper.
If you need to change any setting. It can be done by comparing the "${PROFILE}Preferences" file that is saved
I'd recommend always starting with a clean profile as follows, then setting whatever preferences you want in code. to get a reproducible result.
data_dir = "tmp/remote-profile"
if os.path.exists(data_dir):
shutil.rmtree(data_dir)
options.add_argument("--user-data-dir=tmp/remote-profile")
options.add_argument('--profile-directory=Default')
In the case above the Preferences file will be in tmp/remote-profile/Default/Preferences
Add this below command line argument, which will restrict geolocation feature.
String url = "http://ctrlq.org/maps/where/";
//Chromedriver Version : 2.19.346078
System.setProperty("webdriver.chrome.driver", "CHROMEDRIVERPATH");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
options.addArguments("--enable-strict-powerful-feature-restrictions");
WebDriver driver = new ChromeDriver(options);
driver.get(url);
And other way is after lauching the chrome browser, Through the selenium code implement below steps which will disable the geo location popup.
Go to : chrome://settings/content
Under the location select 'Do not allow any site to track your physical location' option.
Click On Done
I am trying to save an image by using save as option inside a specific folder. I found a way by which I am able to right click on the image which I want to save using save as option. But the problem where I am stuck is after getting the os window which asks where to save the file I am not able to send the desired location because I don't know how to do it. I went through the similar questions asked on this forum but non of them helped so far.
Code is-
For Firefox-
public class practice {
public void pic() throws AWTException{
WebDriver driver;
//Proxy Setting
FirefoxProfile profile = new FirefoxProfile();
profile.setAssumeUntrustedCertificateIssuer(false);
profile.setEnableNativeEvents(false);
profile.setPreference("network.proxy.type", 1);
profile.setPreference("network.proxy.http", "localHost");
profile.setPreference("newtwork.proxy.http_port",3128);
//Download setting
profile.setPreference("browser.download.folderlist", 2);
profile.setPreference("browser.helperapps.neverAsk.saveToDisk","jpeg");
profile.setPreference("browser.download.dir", "C:\\Users\\Admin\\Desktop\\ScreenShot\\pic.jpeg");
driver = new FirefoxDriver(profile);
driver.navigate().to("http://stackoverflow.com/users/2675355/shantanu");
driver.findElement(By.xpath("//*[#id='large-user-info']/div[1]/div[1]/a/div/img"));
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//*[#id='large-user-info']/div[1]/div[1]/a/div/img"))).perform();
action.contextClick().perform();
Robot robo = new Robot();
robo.keyPress(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_V);
// Here I am getting the os window but don't know how to send the desired location
}//method
}//class
For chrome-
public class practice {
public void s() throws AWTException{
WebDriver driver;
System.setProperty("webdriver.chrome.driver","C:\\Users\\Admin\\Desktop\\chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://stackoverflow.com/users/2675355/shantanu");
driver.findElement(By.xpath("//*[#id='large-user-info']/div[1]/div[1]/a/div/img"));
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//*[#id='large-user-info']/div[1]/div[1]/a/div/img"))).perform();
action.contextClick().perform();
Robot robo = new Robot();
robo.keyPress(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_V);
// Here I am getting the os window but don't know how to send the desired location
}
}
There are two things that are going wrong in code.
For Firefox:
You need to set
profile.setPreference("browser.download.dir", "C:\\Users\\Admin\\Desktop\\ScreenShot\\");
not to
profile.setPreference("browser.download.dir", "C:\\Users\\Admin\\Desktop\\ScreenShot\\pic.jpeg");
secondly, you are setting preference browser.download.folderlist, it is browser.download.folderList (L caps in folderList).
Once you have achieved this both, you can use then your Robot class to perform desired operations.
For Chromedriver try out with:
String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
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);
Hope this helps. :)
For Chrome Browser:
Even you can disable the windows dialogue (Save As Dialogue) with the following code snippet. You need to do following settins in the chromedriver preferences:
turn off the download prompt if it appears
set the default directory to download the file
If PDF view plugin is enabled which opens the PDF file in browser, you can disable that so that download can start automatically
Accept any certificate in browser
String downloadFilepath = "/path/to/download/directory/";
Map<String, Object> preferences = new Hashtable<String, Object>();
preferences.put("profile.default_content_settings.popups", 0);
preferences.put("download.prompt_for_download", "false");
preferences.put("download.default_directory", downloadFilepath);
// disable flash and the PDF viewer
preferences.put("plugins.plugins_disabled", new String[]{
"Adobe Flash Player", "Chrome PDF Viewer"});
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", preferences);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
I spent a lot of time to investigate how to download pdf file in firefox browser without Save As popup appearance. It migth be help someone.
After some local investigation, how to download pdf file in firefox without any Save As popup, I found the minimum required preference in firefox profile:
profile.setPreference("pdfjs.disabled", true);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
Of course you can add some additional preferences.
It works in Firefox 45-46 versions.
You partially answered your own question:
the problem where i am stuck is after getting the os window
Selenium is a browser automation tool - os window is not a browser! You will need to use something else. There are many choices, depending on your needs: Sikuli, Robot, AutoIt, ...
Use the same Robot class and press enter to select the "Save" in the Windows dialog box.
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);
if you need to rename it copy the file name in the clipboard and pass like below
StringSelection file = new StringSelection("D:\\image.jpg");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(file, null);
Robot rb = new Robot();
rb.setAutoDelay(2000); // Similar to thread.sleep
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);
rb.keyRelease(KeyEvent.VK_V);
rb.setAutoDelay(2000);
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
Probably not the best solution but you could try using sikuli api to confirm the save for the box that shows up.
The save as box is an OS window.
For Chrome, it will works
String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
WebDriver driver = new ChromeDriver(options);