在 Firefox Addon 中显示目录浏览对话框

Nic*_*ler 2 javascript firefox-addon firefox-addon-sdk

我想让我的用户通过显示一个对话框来选择一个文件夹。

这可能来自 Firefox 插件中的 JavaScript 吗?

在此处输入图片说明

Mak*_*yen 5

是的,有一种简单的方法可以做到这一点。通常的方法是使用nsIFilePicker

与该页面上的示例的主要区别在于,在传递给该init()方法的参数中,您nsIFilePicker.modeGetFoldermode. 此外,考虑到您正在寻找一个目录,您只想包括nsIFilePicker.filterAll过滤器,而不是特定扩展类型的过滤器。

来自 MDN 页面的示例代码,为选择文件夹而修改(并给出了描述性变量名称):

if (window === null || typeof window !== "object") {
    //If you do not already have a window reference, you need to obtain one:
    //  Add a "/" to un-comment the version appropriate for your environment.

    /* Add-on SDK environment:
    var window = require('sdk/window/utils').getMostRecentBrowserWindow();
    //*/

    /* Overlay and bootstrap environments (from almost any context/scope):
    var window = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                           .getService(Components.interfaces.nsIWindowMediator)
                           .getMostRecentWindow("navigator:browser");
    //*/
}


const nsIFilePicker = Components.interfaces.nsIFilePicker;

var filePicker = Components.classes["@mozilla.org/filepicker;1"]
               .createInstance(nsIFilePicker);
filePicker.init(window, "Dialog Title", nsIFilePicker.modeGetFolder);
filePicker.appendFilters(nsIFilePicker.filterAll );

var pickerStatus = filePicker.show();
if (pickerStatus == nsIFilePicker.returnOK 
    || pickerStatus == nsIFilePicker.returnReplace
) {
  var file = filePicker.file;
  // Get the path as string. Note that you usually won't 
  // need to work with the string paths.
  var path = filePicker.file.path;
  // work with returned nsILocalFile...
}
Run Code Online (Sandbox Code Playgroud)