webutil.js: add localStorage/chrome.storage settings.

Add routines to store/read settings in either localStorage or in
chrome.storage.sync (which is synchronized between browsers for
extensions/apps).

Before using chrome.storage.sync the initSettings routine must to
called setup the intermediate cache which speeds up access and allows
multiple setting changes to be coallesced to avoid hitting storage
change frequency limits/quotas.
This commit is contained in:
Joel Martin 2012-09-14 16:18:18 -05:00
parent 51fc3b5f03
commit 3af1c2751b
1 changed files with 61 additions and 0 deletions

View File

@ -118,6 +118,67 @@ WebUtil.eraseCookie = function(name) {
WebUtil.createCookie(name,"",-1);
};
/*
* Setting handling.
*/
WebUtil.initSettings = function(callback) {
var callbackArgs = Array.prototype.slice.call(arguments, 1);
if (chrome && chrome.storage) {
chrome.storage.sync.get(function (cfg) {
WebUtil.settings = cfg;
console.log(WebUtil.settings);
if (callback) {
callback.apply(this, callbackArgs);
}
});
} else {
// No-op
if (callback) {
callback.apply(this, callbackArgs);
}
}
};
// No days means only for this browser session
WebUtil.writeSetting = function(name, value) {
if (chrome && chrome.storage) {
//console.log("writeSetting:", name, value);
if (WebUtil.settings[name] !== value) {
WebUtil.settings[name] = value;
chrome.storage.sync.set(WebUtil.settings);
}
} else {
localStorage.setItem(name, value);
}
};
WebUtil.readSetting = function(name, defaultValue) {
var value;
if (chrome && chrome.storage) {
value = WebUtil.settings[name];
} else {
value = localStorage.getItem(name);
}
if (typeof value === "undefined") {
value = null;
}
if (value === null && typeof defaultValue !== undefined) {
return defaultValue;
} else {
return value;
}
};
WebUtil.eraseSetting = function(name) {
if (chrome && chrome.storage) {
chrome.storage.sync.remove(name);
delete WebUtil.settings[name];
} else {
localStorage.removeItem(name);
}
};
/*
* Alternate stylesheet selection
*/