Auto download pdf files in Firefox

2019-04-02 15:54发布

问题:

I'm doing tests with Selenium and JUnit. I'm trying to export a report (pdf and xls). With Selenium, I click the download link, and do a verifcar to assert that the file is in the correct folder.

I was able to test with the xls, but Firefox always asks what I want to do with the PDF.

The configuration of Firefox, Selenium is this:

String downloadPath = new File("src/test/resources/firefox_download").getAbsolutePath();
firefoxProfile.setPreference("browser.download.dir", downloadPath);
        firefoxProfile.setPreference("browser.download.lastDir", downloadPath);
        firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
        firefoxProfile.setPreference("plugin.disable_full_page_plugin_for_types", "application/pdf,application/vnd.fdf");

        firefoxProfile.setPreference("browser.download.folderList", 2);
        firefoxProfile.setPreference("browser.download.defaultFolder", downloadPath);
        firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf, application/vnd.fdf, application/x-msdos-program, application/x-unknown-application-octet-stream, application/vnd.ms-powerpoint, application/excel, application/vnd.ms-publisher, application/x-unknown-message-rfc822, application/vnd.ms-excel, application/msword, application/x-mspublisher, application/x-tar, application/zip, application/x-gzip,application/x-stuffit,application/vnd.ms-works, application/powerpoint, application/rtf, application/postscript, application/x-gtar, video/quicktime, video/x-msvideo, video/mpeg, audio/x-wav, audio/x-midi, audio/x-aiff"); // tipo específico
        firefoxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);

I can manually change, here:

or here:

But I need to do this programmatically, or test will fail elsewhere (such as the server / sonar)

PS.: Firefox 19

回答1:

you can try to set the MIME type to application/octet-streamso if the browser doesnt know how to handle it, it will pop up a save as dialog