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.
In the JSM scope
File is available without needing to do anything special.
In Bootstrap scope, this must be imported in like so:
Cu.importGlobalProperties( [ "File" ] )
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.
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.
Starting in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5), you can also do this in component code.