Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to determine the extension's directory
    text
    copied!<p>I need to get the path of the extension installed directory from JavaScript.</p> <p>My goal is to write to a JSON file within the extension directory from a Firefox extension. In order to do that, I need to determine the directory in which the extension is installed within the Firefox profile.</p> <p>I use this code: </p> <pre><code>function writeToFile() { var id = "plugin@uua";// The extension's id from install.rdf(i.e. &lt;em:id&gt;) var ext = Components.classes["@mozilla.org/extensions/manager;1"] .getService(Components.interfaces.nsIExtensionManager) .getInstallLocation(id) .getItemLocation(id); var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); file.initWithPath(ext.path); file.append("config.json"); var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"] .createInstance(Components.interfaces.nsIFileOutputStream); foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0); var data = '[ {"id" : "2"} ]'; foStream.write(data, data.length); foStream.close(); </code></pre> <p>It throws the following error: </p> <pre><code>TypeError:Components.classes['@mozilla.org/extensions/manager;1'] is undefined. </code></pre> <p><strong>I essentially need to get the path of the extension automatically from JavaScript.</strong> I double checked the ID of my extension and I also tried writing to files from other extensions with no luck.</p> <hr> <p>Thanks very much for your replies. It didn't let me solve my problem instantly anyway but it forced me to reading Mozilla documentation. I finally got a hang of how it works. Thanks again.</p> <p><strong>Solution to the question above:</strong> </p> <pre><code> Components.utils.import("resource://gre/modules/AddonManager.jsm"); Components.utils.import("resource://gre/modules/FileUtils.jsm"); AddonManager.getAddonByID("plugin_id", function(addon) { var uri = addon.getResourceURI("config.json"); var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); var stringUri = uri.asciiSpec; stringUri = stringUri.replace(new RegExp(/\//g), '\\'); stringUri = stringUri.slice(8); alert(stringUri); file.initWithPath(stringUri); alert(addon.hasResource("config.json")); var stream = FileUtils.openFileOutputStream(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE); stream.write(dataToWrite, dataToWrite.length); stream.close(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload