我需要從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