Directory picker dialog in WebExtension

339 views Asked by At

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.

1

There are 1 answers

5
Xan On

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