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();