如何使用firefox附加sdk保存文本文件?

时间:2014-04-12 11:59:07

标签: firefox-addon-sdk

这是我的main.js:

var widgets = require("sdk/widget");
var {Cc, Ci, Cu} = require("chrome");
var promptSvc = Cc["@mozilla.org/embedcomp/prompt-service;1"].
    getService(Ci.nsIPromptService);
var stringtosave = 'secret information';

var widget = widgets.Widget({
    id: "save_text_button",
    label: "save text",
    contentURL: "http://www.mozilla.org/favicon.ico",
    onClick: function() {
        promptSvc.alert(null, "My Add-on", stringtosave + " saved! ");
    }
});

它可以使用XPCOM警告字符串。

如何将stringtosave保存在PC硬盘上某处的文本文件中?

也许有一个简单的解决方案,也可以使用XPCOM。

2 个答案:

答案 0 :(得分:8)

假设您要使用个人资料目录

const { pathFor } = require('sdk/system');
const path = require('sdk/fs/path');
const file = require('sdk/io/file');

function saveText(name, str){
  var filename = path.join(pathFor('ProfD'), name);
  var textWriter = file.open(filename, 'w');
  textWriter.write(str);
  textWriter.close();
}

function readText(name){
  var filename = path.join(pathFor('ProfD'), name);
  if(!file.exists(filename)){
    return null;
  }
  var textReader = file.open(filename, 'r');
  var str = textReader.read();
  textReader.close();
  return str;
}

答案 1 :(得分:0)

感谢paa的出色回答我可以发布我的增强版main.js:

var widgets = require("sdk/widget");
var {Cc, Ci, Cu} = require("chrome");
var promptSvc = Cc["@mozilla.org/embedcomp/prompt-service;1"].
    getService(Ci.nsIPromptService);
var stringtosave = 'secret information';

//---------------------
const { pathFor } = require('sdk/system');
const path = require('sdk/fs/path');
const file = require('sdk/io/file');

function saveText(name, str){
    var filename = path.join(pathFor('ProfD'), name);
    var textWriter = file.open(filename, 'w');
    textWriter.write(str);
    textWriter.close();
}

function readText(name){
    var filename = path.join(pathFor('ProfD'), name);
    if(!file.exists(filename)){
        return null;
    }
    var textReader = file.open(filename, 'r');
    var str = textReader.read();
    textReader.close();
    return str;
}
//--------------------


var widget = widgets.Widget({
    id: "save_text_button",
    label: "save text",
    contentURL: "http://www.mozilla.org/favicon.ico",
    onClick: function() {
        var stringtoshow = readText('secret_message.txt');
        console.log('this message was saved before: '+stringtoshow);

        saveText('secret_message.txt',stringtosave);

        promptSvc.alert(null, "My Add-on", stringtosave + " saved! ");

    }
});

console.log('path: '+pathFor('ProfD'));