Chrome headless selenium driver doesn’t download files by default: security feature

Chrome selenium driver headless mode by default doesn’t allow downloading files as its a security feature. Firefox doesn’t have this limitation, but at work we’re using Chrome as its more stable in our Behaviour Driven Development (BDD) tests. We need headless to work as we are running BDD tests in a docker container. Stackoverflow mention here, well known security feature (bug), java solution.
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");

ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--headless");
options.addArguments("--disable-extensions"); //to disable browser extension popup

ChromeDriverService driverService = ChromeDriverService.createDefaultService();
ChromeDriver driver = new ChromeDriver(driverService, options);
Map commandParams = new HashMap<>();
commandParams.put("cmd", "Page.setDownloadBehavior");

Map params = new HashMap<>();
params.put("behavior", "allow");
params.put("downloadPath", "//home//vaibhav//Desktop");
commandParams.put("params", params);

ObjectMapper objectMapper = new ObjectMapper();
HttpClient httpClient = HttpClientBuilder.create().build();
String command = objectMapper.writeValueAsString(commandParams);
String u = driverService.getUrl().toString() + "/session/" + driver.getSessionId() + "/chromium/send_command";

HttpPost request = new HttpPost(u);
request.addHeader("content-type", "application/json");
request.setEntity(new StringEntity(command));
httpClient.execute(request);

driver.get("http://www.seleniumhq.org/download/");
driver.findElement(By.linkText("32 bit Windows IE")).click();
However, the solution by itself didn’t work for our Work angular button. It works for links and html buttons but the angular button is doing something different. French guy ingenious suggestion that works. Working solution = instead of clicking buttons (problematic), fetch the resource that you’re trying to download

Leave a Reply

Your email address will not be published. Required fields are marked *