我需要从 JavaScript 获取扩展安装目录的路径。
我的目标是从 Firefox 扩展写入扩展目录中的 JSON 文件。为此,我需要确定扩展在 Firefox 配置文件中的安装目录。
我使用这段代码:
function writeToFile()
{
var id = "plugin@uua";// The extension's id from install.rdf(i.e. <em:id>)
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();
它抛出以下错误:
TypeError:Components.classes['@mozilla.org/extensions/manager;1'] is undefined.
我基本上需要从 JavaScript 自动获取扩展的路径。 我仔细检查了我的扩展程序的 ID,我也尝试从其他扩展程序写入文件,但没有成功。
非常感谢您的回复。它并没有让我立即解决我的问题,但它迫使我阅读 Mozilla 文档。我终于明白了它是如何工作的。再次感谢。
上述问题的解答:
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();
最佳答案
从 Firefox 4 开始,您应该使用 Add-on Manager API :
Components.utils.import("resource://gre/modules/AddonManager.jsm");
AddonManager.getAddonByID(id, function(addon)
{
var uri = addon.getResourceURI("config.json");
if (uri instanceof Components.interfaces.nsIFileURL)
writeToFile(uri.file);
});
请注意,新 API 是异步的,获取有关扩展程序的数据可能需要一些时间。此外,您需要指定 <em:unpack>true</em:unpack>
flag在你的install.rdf
,否则你的扩展将不会在安装时解压(出于性能原因)并且磁盘上将没有对应于 config.json
的文件(它将是打包的 XPI 文件中的一个位置)。写入扩展目录还有另一个问题:当扩展更新时,那里的所有文件都会被替换。一个更好的主意可能是写入配置文件目录中的文件,这样您就不需要牺牲性能。
可以使用 FileUtils.jsm 简化写入文件的操作:
Components.utils.import("resource://gre/modules/FileUtils.jsm");
var stream = FileOutputStream.openFileOutputStream(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE);
stream.write(data, data.length);
stream.close();
关于javascript - 如何确定扩展的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10033618/