解决这个问题的方法是创建自己的存储 API。您已经确定 localStorage 是同步的,而 Chrome 存储是异步的,但这个问题很容易解决,只需将所有内容都视为异步即可。
创建您自己的 API,然后使用它代替所有其他调用。在您的代码中快速查找/替换可以用新 API 替换 localStorage 调用。
function LocalStorageAsync() {
/**
* Parses a boolean from a string, or the boolean if an actual boolean argument is passed in.
*
* @param {String|Boolean} bool A string representation of a boolean value
* @return {Boolean} Returns a boolean value, if the string can be parsed as a bool.
*/
function parseBool(bool) {
if (typeof bool !== 'string' && typeof bool !== 'boolean')
throw new Error('bool is not of type boolean or string');
if (typeof bool == 'boolean') return bool;
return bool === 'true' ? true : false;
}
/**
* store the key value pair and fire the callback function.
*/
this.setItem = function(key, value, callback) {
if(chrome && chrome.storage) {
chrome.storage.local.set({key: key, value: value}, callback);
} else {
var type = typeof value;
var serializedValue = value;
if(type === 'object') {
serializedValue = JSON.stringify(value);
}
value = type + '::typeOf::' + serializedValue;
window.localStorage.setItem(key, value);
callback();
}
}
/**
* Get the item from storage and fire the callback.
*/
this.getItem = function(key, callback) {
if(chrome && chrome.storage) {
chrome.storage.local.get(key, callback);
} else {
var stronglyTypedValue = window.localStorage.getItem(key);
var type = stronglyTypedValue.split('::typeOf::')[0];
var valueAsString = stronglyTypedValue.split('::typeOf::')[1];
var value;
if(type === 'object') {
value = JSON.parse(valueAsString);
} else if(type === 'boolean') {
value = parseBool(valueAsString);
} else if(type === 'number') {
value = parseFloat(valueAsString);
} else if(type === 'string') {
value = valueAsString;
}
callback(value);
}
}
}
// usage example
l = new LocalStorageAsync();
l.setItem('test',[1,2,3], function() {console.log('test');});
l.getItem('test', function(e) { console.log(e);});
下面这个解决方案克服的一个问题是,除了将所有内容都视为异步之外,它还解释了 localStorage 将所有内容转换为字符串这一事实。通过将类型信息保留为元数据,我们确保 getItem 操作的输出与输入的数据类型相同。
此外,使用工厂模式的变体,您可以创建两个具体的内部子类,并根据环境返回适当的子类:
function LocalStorageAsync() {
var private = {};
private.LocalStorage = function() {
function parseBool(bool) {
if (typeof bool !== 'string' && typeof bool !== 'boolean')
throw new Error('bool is not of type boolean or string');
if (typeof bool == 'boolean') return bool;
return bool === 'true' ? true : false;
}
this.setItem = function(key, value, callback) { /* localStorage impl... */ };
this.getItem = function(key, callback) { /* ... */ };
};
private.ChromeStorage = function() {
this.setItem = function(key, value, callback) { /* chrome.storage impl... */ };
this.getItem = function(key, callback) { /* ... */ };
}
if(chrome && chrome.storage)
return new private.ChromeStorage();
else
return new private.LocalStorage();
};