判断浏览器是否支持localStorage
function isLocalStorageUsable(){
const localStorageTestKey = '_localStorage_support_test';
const localStorageTestValue = 'test';
let isSupport = false;
try{
localStorage.setItem(localStorageTestKey,localStorageTestValue)
if(localStorage.getItem(localStorageTestKey) === localStorageTestValue){
isSupport = true;
}
localStorage.removeItem(localStorageTestKey);
return isSupport;
}catch(e){
if(e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED'){
console.log('localStorage 存储已达上限!')
}else{
console.warn('当前浏览器不支持 localStorage!')
}
}
return isSupport
}
避免多次调用该函数
ready(){
if(isSupport === null){
isSupport = isLocalStorageUsable()
}
if(isSupport) {
return Promise.resolve()
}
return Promise.reject()
}
处理key为对象的情况
如果可以的值是对象,那么会隐式的调用 toString() 方法。这会导致key的值都变成 [object Object],容易造成key重复
避免key是对象而覆盖其他值
function normalizeKey(key){
if(typeof key !== 'string'){
console.warn(`${key} used as a key, but it is not a string`);
key = String(key);
}
return key
}
将value进行序列化
function serialize(value, callback) {
try{
const valueString = JSON.stringify(value);
callback( null, valueString);
}catch(e) {
console.log(e);
}
}
整体调用
setItem(key, value){
key = normalizeKey(key);
return ready().then(()=>{
if (value === undefined) {
value = null;
}
serialize(value, (error, valueString)=>{
if (error) {
return Promise.rehect(error);
}
try{
localStorage.setItem(key, valueString);
return Promise.resolve();
} catch(e) {
return Promise.reject(e)
}
})
})
}
组件封装
let isSupport = null
function isLocalStorageUsable(){
const localStorageTestKey = '_localStorage_support_test';
const localStorageTestValue = 'test';
let isSupport = false;
try{
localStorage.setItem(localStorageTestKey,localStorageTestValue)
if(localStorage.getItem(localStorageTestKey) === localStorageTestValue){
isSupport = true;
}
localStorage.removeItem(localStorageTestKey);
return isSupport;
}catch(e){
if(e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED'){
console.log('localStorage 存储已达上限!')
}else{
console.warn('当前浏览器不支持 localStorage!')
}
}
return isSupport
}
function serialize(value, callback) {
try{
const valueString = JSON.stringify(value);
callback( null, valueString);
}catch(e) {
console.log(e);
}
}
function normalizeKey(key){
if(typeof key !== 'string'){
console.warn(`${key} used as a key, but it is not a string`);
key = String(key);
}
return key
}
function ready(){
if(isSupport === null){
isSupport = isLocalStorageUsable()
}
if(isSupport) {
return Promise.resolve()
}
return Promise.reject()
}
function setItem(key, value){
key = normalizeKey(key);
return ready().then(()=>{
if (value === undefined) {
value = null;
}
serialize(value, (error, valueString)=>{
if (error) {
return Promise.rehect(error);
}
try{
localStorage.setItem(key, valueString);
return Promise.resolve();
} catch(e) {
return Promise.reject(e)
}
})
})
}
export default setItem