2

我以这种方式在我的 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, '');

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

4

1 回答 1

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

于 2013-02-23T07:53:55.160 回答