2014-04-12 58 views
4

這裏是我main.js:如何使用Firefox附加sdk保存文本文件?

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。

+0

這段代碼的偉大工程的方式,是一個很好的從附加sdk使用XPCOM的教程。該按鈕應該出現在瀏覽器的右下角。而且它很容易運行,因爲這個main.js是你所需要的。 – Andromeda

回答

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; 
} 
+0

這個作品迷人 – Andromeda

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')); 
相關問題