当用户删除脱机数据时,保留Firefox附加组件localStorage

时间:2012-11-20 04:11:15

标签: javascript firefox-addon local-storage

我正在以这种方式在我的Firefox插件中使用localStorage:

var ioService = Components.classes['@mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService);
var scriptSecManager = Components.classes['@mozilla.org/scriptsecuritymanager;1'].getService(Components.interfaces.nsIScriptSecurityManager);
var domStorageManager = Components.classes['@mozilla.org/dom/storagemanager;1'].getService(Components.interfaces.nsIDOMStorageManager);
var uri = ioService.newURI('http://example.com/addon/', null, null);
var principal = scriptSecManager.getNoAppCodebasePrincipal ? scriptSecManager.getNoAppCodebasePrincipal(uri) : scriptSecManager.getCodebasePrincipal(uri);
var localStorage = domStorageManager.getLocalStorageForPrincipal(principal, '');

一切正常,但当用户删除“离线数据”时,存储将被清除。我该如何解决它?

1 个答案:

答案 0 :(得分:0)

使用首选项服务将数据存储在用户的个人资料中。

var prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService),
    prefs = prefService.getBranch("extensions.YOUREXTENSIONABBREVIATIONHERE.");

var stringValue = "My Name",
    booleanValue = true,
    numberValue = 55;

prefs.setCharPref("stringParam", stringValue);
prefs.setBoolPref("booleanParam", booleanValue);
prefs.setCharPref("numberParam", ''+numberValue);

prefService.savePrefFile(null);   // only to force an immediate save

stringValue = prefs.getCharPref("stringParam");
booleanValue = prefs.getBoolPref("booleanParam");
numberValue = parseInt(prefs.getCharPref("numberParam"), 10);

将defaults.js文件放在defaults / preferences文件夹中,并初始化新用户的首选项。如果您尝试检索不存在的首选项并且无法检查它是否存在,则会收到错误。

看这里:

https://developer.mozilla.org/en-US/docs/Adding_preferences_to_an_extension