我需要从JavaScript获取扩展安装目录的路径。如何确定扩展的目录
我的目标是从Firefox扩展中写入扩展目录中的JSON文件。为了做到这一点,我需要确定在Firefox配置文件中安装扩展的目录。
我用这个代码:
function writeToFile()
{
var id = "[email protected]";// 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();
我想你需要确保你的扩展,以写入文件的安装目录解压。 – erikvold 2012-04-05 18:20:03
,因此您可能希望将该文件保存在用户的配置文件目录中。 – erikvold 2012-04-05 18:20:22