Using the DOM File API in chrome code 编辑

If you want to use the DOM File API in chrome code, you can do so without restriction. In fact, you get one bonus feature: you can create File objects 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.

Scope Availability

In the JSM scope Fileis available without needing to do anything special.

In Bootstrap scope, this must be imported in like so:

Cu.importGlobalProperties( [ "File" ] )

Accessing a file by hard-coded pathname

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

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

Cross platform note: However using hard-coded paths raises cross platform issues since it uses a platform-dependent path separator (here "/"). In the XUL/Mozilla platform there isn't sadly an equivalent to Java File.pathSeparator (the system-dependent path-separator character). So the good practice is to avoid trying to determine and to use the path separator at all. Instead, use the nsIFile::append() method as explained in the next section.

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.createFromNsIFile(dsFile);

This uses the directory service to locate the profile directory (with the location key "ProfD", see below for more details), then appends the name of the file we want to work with by calling nsIFile.append(). Finally, we instantiate the File object by calling File.createFromNsIFile.

Other such keys as the "ProfD" key are available, check the known locations.

Notes

Starting in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5), you can also do this in component code.

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:93 次

字数:4214

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文