0

From a Firefox add-on implemented as a WebExtension, I'd like to let the user choose a local directory, if possible with the standard directory picker dialog (a variant of the "open file" dialog).

Can this be done from a WebExtension? If so, how?

(In regular JavaScript/HTML on a website, it's not possible for security reasons. See e.g. Select directory path in JavaScript. But as an Add-on should be somewhat trusted by the user, I wonder whether it's possible there.)

Context: I'd like to make a simple bulk downloader, that lets the user choose a target directory for multiple to-be-downloaded files rather than just throwing all of them into the default Downloads folder, but without showing the "Save as" dialog for each individual download.

das-g
  • 9,718
  • 4
  • 38
  • 80

1 Answers1

0

As far as I'm aware, WebExtensions can't write to arbitrary folders even with user intervention.

However, you can partially achieve your requirement if you accept to use a subfolder inside the default donwloads folder.

browser.downloads API allows you to put a "suggested filename" that contains a folder in it. It can only be a relative path, and it's relative to the default folder.

If you're initiating the download yourself:

function dowloadToFolder(url, name, subfolder) {
  browser.downloads.download({
    url: url,
    filename: `${subfolder}/${name}`
  });
}

If you don't know the final name, or the user initiates the download, sadly Firefox does not have an equivalent of Chrome's onDeterminingFilename event. But for a bulk downloader you should be the one initiating it, and not knowing what filename the server will report can in principle be checked with a HEAD request before the download (haven't tested).

Xan
  • 74,770
  • 16
  • 179
  • 206
  • I'm fine with being limited to subfolders of the default download folder and I indeed plan to pass the folder to as part of the filename to `browser.downloads.download()`. This question though is about how to query the user for what (sub)folder to use. So while this answer is very informative, it doesn't answer the question at all. – das-g Nov 09 '18 at 19:45
  • 1
    Then no; I'm afraid you can't show the directory picker or even query which directories already exist. The best you can do is a setting user has to type in manually. – Xan Nov 09 '18 at 19:46
  • Can you put the information from your comment into an answer, maybe quoting some sources? Because that _does_ answer the question at hand. – das-g Nov 09 '18 at 21:13
  • Also, do you have any idea on why it's not (been made) possible? Is it just something that hasn't been implemented/specified yet, and thus a feature request to that regard would have good chances to be considered? Or has it consciously been forbidden, e.g. due to the same security considerations as for JavaScript from the web? – das-g Nov 09 '18 at 21:20
  • 1
    Set the saveAs property to true to ask the user about the subdirectory. – Smile4ever Dec 05 '18 at 18:16