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

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