localStorage自定义设置过期时间

localStorage简单封装:

Catch = {

	/**
	 * localStorage写入
	 * @param {Object} key
	 * @param {Object} stringVal
	 * @param {Object} time
	 */
	setStorage: function(key, stringVal, time){
		try{
			if(!localStorage){
				return false;
			}
			if(!time || isNaN(time)){
				time = 60;
			}
			var cacheExpireDate = (new Date() - 1) + time * 1000;
			var cacheVal = {val:stringVal, exp:cacheExpireDate};
			localStorage.setItem(key, JSON.stringify(cacheVal));
		}catch(e){
			console.log(e);
		}
	},
	
	/**
	 * localStorage读取
	 * @param {Object} key
	 */
	getStorage: function(key){
		try{
			if(!localStorage){
				return false;
			}
			var cacheVal = localStorage.getItem(key);
			var result = JSON.parse(cacheVal);
			var now = new Date() - 1;
			if(!result){
				return null;
			}
			if(now > result.exp){
				this.remove(key);					
				return "";
			}
			return result.val;
		}catch(e){
			//this.remove(key);
			return null;
		}
	},
	
	/**
	 * localStorage删除
	 * @param {Object} key
	 */
	delStorage : function(key){
		if(!localStorage){
			return false;
		}
		localStorage.removeItem(key);
	},
	
	/**
	 * localStorage删除
	 */
	delAllStorage : function(){
		if(!localStorage){
			return false;
		}
		localStorage.clear();
	}
	
}
基本调用:

1、存储:Catch.setStorage("userName", "angbike", 1*24*60*60);
2、获取:Catch.getStorage("userName");
3、删除特定存储内容:Catch.delStorage("userName");
4、删除全部内容:Catch.delAllStorage();