firefox addon - 開發firefox addon,如何將數據保存到本地文件中

由於自己比較喜歡使用firefox的一個書籤addon,但是總覺得功能有點不滿足,所以決定自己修改一下。下載來它的源代碼就開始。碰到一個核心的問題,就是如何寫數據到本地文件。

 

我印象中記得,js作爲一種客戶端的腳本(大多數情況下),是沒有這個權限的,所以覺得不太可能。但是後來想到每個插件都會有自己的配置信息,肯定要寫到本地系統的。除此之外,有的 addon比如提供書籤功能的,肯定要將用戶的書籤保存到本地文件。顯然在插件中是可以做到的,雖然我不太確定是不是通過js,因爲它有可能是通過firefox瀏覽器提供的xpcom API來操作的,或者通過其它的component來實現的。

 

 

我在mozilla上面找了不少資料,

You access the file system using Mozilla XPCOM components.

確認了保存數據到本地是可行的。

 

下面就是一個將數據保存到本地文件的示例:

 

 setFileContent: function(file, str) {
  try {
   var fos = Components.classes['@mozilla.org/network/file-output-stream;1']
      .createInstance(Components.interfaces.nsIFileOutputStream);
   fos.init(file, 0x02 | 0x08 | 0x20, 0664, 0);
   var os = Components.classes['@mozilla.org/intl/converter-output-stream;1']
      .createInstance(Components.interfaces.nsIConverterOutputStream);
   os.init(fos, 'UTF-8', 4096, Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
   os.writeString(str);
   os.close();
   fos.close();
  } catch(e) {
   this.log(e);
  }
 }

 

// file is nsIFile, data is a string
var otream = Components.classes["@mozilla.org/network/file-output-stream;1"].
             createInstance(Components.interfaces.nsIFileOutputStream);

// use 0x02 | 0x10 to open file for appending.
otream.init(file, 0x02 | 0x08 | 0x20, 0666, ostream.DEFER_OPEN); 
// write, create, truncate

var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
                createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(data);
Components.utils.import("resource://gre/modules/NetUtil.jsm");
NetUtil.asyncCopy(istream, ostream);

 

參考:

https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO

http://stackoverflow.com/questions/2639400/where-firefox-extensions-store-data

https://developer.mozilla.org/en-US/search?q=Components.classes

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章