Chrome profile to disable "Know your location" pop up - java

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

Related

How to click "Allow" automatically on Google Chrome pop-up using Selenium + Java

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

Could not set download.prompt_for_download false for avoiding popup when downloading a file in an Electron application

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

Downloading a script file using selenium giving, This type of file can harm your computer popup

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 !!

how to change file download location in Webdriver while using chrome driver/firefox driver

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

Selenium 2 chrome driver preferences java equivalent to RubyBindings

I've been looking for a way to set the driver preferences for chrome driver using java for the past two days with no luck.
I have however found a solution in ruby VIA RubyBindings and would like to know if there is a java equivalent line I can use for this.
The ruby code is the following:
profile = Selenium::WebDriver::Chrome::Profile.new
profile['download.prompt_for_download'] = false
profile['download.default_directory'] = "/path/to/dir"
driver = Selenium::WebDriver.for :chrome, :profile => profile
While searching I found that chrome does not have a profiler I could use like the FirefoxProfile class, so I started using the DesireCapabilities class instead. After further investigation into this problem I found that I could set the "switches" and "prefs" VIA capabilities.setCapabilitiy and ended up with the following:
Map<String, String> prefs = new Hashtable<String, String>();
prefs.put("download.prompt_for_download", "false");
prefs.put("download.default_directory", "/path/to/dir");
prefs.put("download.extensions_to_open", "pdf");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.prefs", prefs);
dr = new ChromeDriver(capabilities);
However I was not able to get this working, the default download directory was never changed to the specified directory once started. I am unsure if there is a problem with how I am trying to set this capability or if the problem lies elsewhere.
In the end I eventually used the solution proposed here:
http://dkage.wordpress.com/2012/03/10/mid-air-trick-make-selenium-download-files/
but I would like to know if it is possible to do this more cleanly but just setting the preferences directly instead of using the UI
Any help is appreciated, Thanks!
Update:
Surprisingly after updating Selenium 2 to version 2.24.1 (and to windows chrome 22), the code above with the Maps work as expected, the only problem now is that they deprecated the the use of the constructor ChromeDriver(DesiredCapabilities capabilities), and instead recommend I use the ChromeOptions class, which I cannot get working for the above scenario.
Below is the wiki page explaining the use of both ChromeOptions and DesiredCapabilities:
http://code.google.com/p/chromedriver/wiki/CapabilitiesAndSwitches
The Ruby bindings actually expands that to:
{
"download": {
"prompt_for_download": false,
"default_directory": "/path/to/dir"
}
}
Try building your Java prefs object like that and see if it works. The string vs boolean false could also be an issue.
Try this (Forgive my java which is quite rusty, but hopefully you get the idea)
Dictionary download = new Dictionary();
download["default_directory"] = "/path/to/dir";
Dictionary prefs = new Dictionary();
prefs["browser"] = download;
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.prefs", prefs);
WebDriver driver = new ChromeDriver(capabilities);
Update: I just browsed the code and it seems that what I suggested above probably won't work. The ruby chrome profile class creates zip file with chrome profile file structure in it to support chrome preference. I couldn't find such facility code in java. There is a Firefox profile in java that does the simliar thing for firefox, but obviously that won't work for chrome. So in short, this feature is not supported yet in java.
Newer versions (I tested Chrome 44.0.2403.125, Selenium 2.47.1, and ChromeDriver 2.17.340128) work with the following:
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("download.default_directory", "/path/to/directory");
options.setExperimentalOption("prefs", prefs);
ChromeDriver chromeDriver = new ChromeDriver(options);

Categories