MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/MDN-dev-survey

使用 DOM 檔案 API 再FireFox外觀代碼上

翻譯不完整。請協助 翻譯此英文文件

如果你想使用如果你想使用 DOM 檔案 API 在FireFox外觀代碼上面,你可以沒有任何限制的這樣做。事實上你得到了一個特別的功能。你可以建立你可以建立 File 物件 specifying the path of the file on the user's computer. This only works from privileged code, so web content can't do it. This protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. If you pass a path to the File constructor from unprivileged code (such as web content), an exception will be thrown.

Accessing a file by hard-coded pathname

To reference a file by its path, you can simply use a string literal:

var file = File("path/to/some/file");

Accessing files in a special directory

You can also use the directory service to obtain and build the path to a file to access. For example, let's say your add-on needs to access a file in the user's profile. You can do so like this:

var dsFile = Components.classes["@mozilla.org/file/directory_service;1"]
                    .getService(Components.interfaces.nsIProperties)
                    .get("ProfD", Components.interfaces.nsIFile);

dsFile.append("myfilename.txt");

var file = File(dsFile.path);

This uses the directory service to locate the profile directory ("ProfD"), then appends the name of the file we want to work with by calling nsIFile.append(). Finally, we instantiate the File object by passing the string returned by nsIFile.path() to the File constructor.

You can even simplify this further! You can actually pass the nsIFile object itself directly to the File constructor, resulting in the following code:

var dsFile = Components.classes["@mozilla.org/file/directory_service;1"]
                    .getService(Components.interfaces.nsIProperties)
                    .get("ProfD", Components.interfaces.nsIFile);

dsFile.append("myfilename.txt");

var file = File(dsFile);

See also

文件標籤與貢獻者

 此頁面的貢獻者: irvinfly, orinx
 最近更新: irvinfly,