Access to file download dialog in Firefox in Selenium.


We can access file download dialog in Firefox in Selenium. For this we have to first modify the default directory where the downloaded file gets stored. This is done by the addpreference method.

p.addPreference("browser.download.folderList", 2);

Then, define the new path of the download directory.

Finally, we shall ignore the save to disk and open file options in dialog for the file types via their MIME code. The addPreference method can be called with the help of FirefoxOptions class.

Example

Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.util.concurrent.TimeUnit;
public class FileDwnloadWithoutDialg{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      // instance of FirefoxOptions class
      FirefoxOptions profile = new FirefoxOptions();
      // adding browser preferences with addPreference method profile.addPreference("browser.download.folderList", 2);
      // location of downloaded file
      profile.addPreference("browser.download.dir", "C:\Users\ghs6kor\Documents\Download");
      profile.addPreference("browser.helperApps.neverAsk.openFile", "text/csv,application/x-msexcel,application/excel," + "application/x-excel,application/vnd.ms-excel," + "image/png,image/jpeg,text/html,text/plain," + "application/msword,application/xml");
profile.addPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/x-msexcel," + "application/excel," + "application/x-excel," +"application/vnd.ms excel,image/png,image/jpeg,text/html," +"text/plain,application/msword,application/xml");
      // connecting browser options to webdriver
      WebDriver driver = new FirefoxDriver(profile);
      driver.get("https://the-internet.herokuapp.com/download");
      //maximize window
      driver.manage().window().maximize();
      // identify element and start download
      driver.findElement(By.linkText("xls-sample3.xls")).click();
   }
}

Updated on: 28-Dec-2020

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements