简体   繁体   中英

Keep Firefox add-on localStorage when user removes offline data

I'm using localStorage in my Firefox add-on in this way:

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, '');

All works fine, but when user removes "offline data" storage is cleared. How can i workround it?

Use the preferences service to store the data in the user's profile.

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);

Put a defaults.js file in your defaults/preferences folder and initialize preferences for a new user. You'll get an error if you try to retrieve a preference that doesn't exist and there's no way to check if it exists.

Look here:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM