分享一个web存储方法
https://github.com/zhujiasheng/jquery-cookie/blob/master/src/jquery.cookie.js
https://github.com/WQTeam/web-storage-cache
https://github.com/jeromegn/Backbone.localStorage/blob/master/backbone.localStorage.js#L63
/*
* WebStorageCache - 0.0.3
* https://github.com/WQTeam/web-storage-cache
*
* This is free and unencumbered software released into the public domain.
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.WebStorageCache = factory();
}
}(this, function () {
"use strict";
var _maxExpireDate = new Date('Fri, 31 Dec 9999 23:59:59 UTC');
var _defaultExpire = _maxExpireDate;
// https://github.com/jeromegn/Backbone.localStorage/blob/master/backbone.localStorage.js#L63
var defaultSerializer = {
serialize: function (item) {
return JSON.stringify(item);
},
// fix for "illegal access" error on Android when JSON.parse is
// passed null
deserialize: function (data) {
return data && JSON.parse(data);
}
};
function _extend (obj, props) {
for (var key in props) obj[key] = props[key];
return obj;
}
/**
* https://github.com/gsklee/ngStorage/blob/master/ngStorage.js#L52
*
* When Safari (OS X or iOS) is in private browsing mode, it appears as
* though localStorage is available, but trying to call .setItem throws an
* exception below: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was
* made to add something to storage that exceeded the quota."
*/
function _isStorageSupported (storage) {
var supported = false;
if (storage && storage.setItem ) {
supported = true;
var key = '__' + Math.round(Math.random() * 1e7);
try {
storage.setItem(key, key);
storage.removeItem(key);
} catch (err) {
supported = false;
}
}
return supported;
}
// get storage instance
function _getStorageInstance (storage) {
var type = typeof storage;
if (type === 'string' && window[storage] instanceof Storage) {
return window[storage];
}
return storage;
}
function _isValidDate (date) {
return Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date.getTime());
}
function _getExpiresDate (expires, now) {
now = now || new Date();
if (typeof expires === 'number') {
expires = expires === Infinity ?
_maxExpireDate : new Date(now.getTime() + expires * 1000);
} else if (typeof expires === 'string') {
expires = new Date(expires);
}
if (expires && !_isValidDate(expires)) {
throw new Error('`expires` parameter cannot be converted to a valid Date instance');
}
return expires;
}
// http://crocodillon.com/blog/always-catch-localstorage-security-and-quota-exceeded-errors
function _isQuotaExceeded(e) {
var quotaExceeded = false;
if (e) {
if (e.code) {
switch (e.code) {
case 22:
quotaExceeded = true;
break;
case 1014:
// Firefox
if (e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
quotaExceeded = true;
}
break;
}
} else if (e.number === -2147024882) {
// Internet Explorer 8
quotaExceeded = true;
}
}
return quotaExceeded;
}
// cache item constructor
function CacheItemConstructor (value, exp) {
// createTime
this.c = (new Date()).getTime();
exp = exp || _defaultExpire;
var expires = _getExpiresDate(exp);
// expiresTime
this.e = expires.getTime();
this.v = value;
}
function _isCacheItem(item) {
if (typeof item !== 'object') {
return false;
}
if(item) {
if('c' in item && 'e' in item && 'v' in item) {
return true;
}
}
return false;
}
// check cacheItem If effective
function _checkCacheItemIfEffective(cacheItem) {
var timeNow = (new Date()).getTime();
return timeNow < cacheItem.e;
}
function _checkAndWrapKeyAsString(key) {
if (typeof key !== 'string') {
console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
return key;
}
// cache api
var CacheAPI = {
set: function (key, value, options) {},
get: function (key) {},
delete: function (key) {},
// Try the best to clean All expires CacheItem.
deleteAllExpires: function() {},
// Clear all keys
clear: function () {},
// Add key-value item to memcached, success only when the key is not exists in memcached.
add: function (key, options) {},
// Replace the key's data item in cache, success only when the key's data item is exists in cache.
replace: function (key, value, options) {},
// Set a new options for an existing key.
touch: function (key, exp) {}
};
// cache api
var CacheAPIImpl = {
set: function(key, val, options) {
key = _checkAndWrapKeyAsString(key);
options = _extend({force: true}, options);
if (val === undefined) {
return this.delete(key);
}
var value = defaultSerializer.serialize(val);
var cacheItem = new CacheItemConstructor(value, options.exp);
try {
this.storage.setItem(key, defaultSerializer.serialize(cacheItem));
} catch (e) {
if (_isQuotaExceeded(e)) { //data wasn't successfully saved due to quota exceed so throw an error
this.quotaExceedHandler(key, value, options, e);
} else {
console.error(e);
}
}
return val;
},
get: function (key) {
key = _checkAndWrapKeyAsString(key);
var cacheItem = null;
try{
cacheItem = defaultSerializer.deserialize(this.storage.getItem(key));
}catch(e){
return null;
}
if(_isCacheItem(cacheItem)){
if(_checkCacheItemIfEffective(cacheItem)) {
var value = cacheItem.v;
return defaultSerializer.deserialize(value);
} else {
this.delete(key);
}
}
return null;
},
delete: function (key) {
key = _checkAndWrapKeyAsString(key);
this.storage.removeItem(key);
return key;
},
deleteAllExpires: function() {
var length = this.storage.length;
var deleteKeys = [];
var _this = this;
for (var i = 0; i < length; i++) {
var key = this.storage.key(i);
var cacheItem = null;
try {
cacheItem = defaultSerializer.deserialize(this.storage.getItem(key));
} catch (e) {}
if(cacheItem !== null && cacheItem.e !== undefined) {
var timeNow = (new Date()).getTime();
if(timeNow >= cacheItem.e) {
deleteKeys.push(key);
}
}
}
deleteKeys.forEach(function(key) {
_this.delete(key);
});
return deleteKeys;
},
clear: function () {
this.storage.clear();
},
add: function (key, value, options) {
key = _checkAndWrapKeyAsString(key);
options = _extend({force: true}, options);
try {
var cacheItem = defaultSerializer.deserialize(this.storage.getItem(key));
if (!_isCacheItem(cacheItem) || !_checkCacheItemIfEffective(cacheItem)) {
this.set(key, value, options);
return true;
}
} catch (e) {
this.set(key, value, options);
return true;
}
return false;
},
replace: function (key, value, options) {
key = _checkAndWrapKeyAsString(key);
var cacheItem = null;
try{
cacheItem = defaultSerializer.deserialize(this.storage.getItem(key));
}catch(e){
return false;
}
if(_isCacheItem(cacheItem)){
if(_checkCacheItemIfEffective(cacheItem)) {
this.set(key, value, options);
return true;
} else {
this.delete(key);
}
}
return false;
},
touch: function (key, exp) {
key = _checkAndWrapKeyAsString(key);
var cacheItem = null;
try{
cacheItem = defaultSerializer.deserialize(this.storage.getItem(key));
}catch(e){
return false;
}
if(_isCacheItem(cacheItem)){
if(_checkCacheItemIfEffective(cacheItem)) {
this.set(key, this.get(key), {exp: exp});
return true;
} else {
this.delete(key);
}
}
return false;
}
};
/**
* Cache Constructor
*/
function CacheConstructor (options) {
// default options
var defaults = {
storage: 'localStorage',
exp: Infinity //An expiration time, in seconds. default never .
};
var opt = _extend(defaults, options);
var expires = opt.exp;
if (expires && typeof expires !== 'number' && !_isValidDate(expires)) {
throw new Error('Constructor `exp` parameter cannot be converted to a valid Date instance');
} else {
_defaultExpire = expires;
}
var storage = _getStorageInstance(opt.storage);
var isSupported = _isStorageSupported(storage);
this.isSupported = function () {
return isSupported;
};
if (isSupported) {
this.storage = storage;
this.quotaExceedHandler = function (key, val, options, e) {
console.warn('Quota exceeded!');
if (options && options.force === true) {
var deleteKeys = this.deleteAllExpires();
console.warn('delete all expires CacheItem : [' + deleteKeys + '] and try execute `set` method again!');
try {
options.force = false;
this.set(key, val, options);
} catch (err) {
console.warn(err);
}
}
};
} else { // if not support, rewrite all functions without doing anything
_extend(this, CacheAPI);
}
}
CacheConstructor.prototype = CacheAPIImpl;
return CacheConstructor;
}));
//使用方式
function saveString_Obj(strName,strVal){
if(typeof strVal === 'object'){
strVal =JSON.stringify(strVal);
}
let wsCache = new WebStorageCache();
wsCache.set(strName, strVal, {exp : 300});
}
分享一个web存储方法的更多相关文章
- 分享一个web应用程序池管理工具
因为项目在联调阶段由于各种各样的原因需要重启应用程序池,而调试服务器基本都需要远登操作.同样的情况也会发生在线上,如果公司权限控制得比较严格,每次都要多部门的服务器权限申请的话有点麻烦, 所以抽点时间 ...
- 分享一个Web弹框类
using System; using System.Text; namespace Core { /// <summary> /// MessageBox 的摘要说明. /// < ...
- web存储方法,现成代码
1.cookie的设置与取用 function setCookie(cname,cvalue,exdays){ var d = new Date(); d.setTime(d.getTime()+(e ...
- 分享一个web安全学习站点
大神建议: https://blog.knownsec.com/Knownsec_RD_Checklist/v3.0.html#FMID_1218170279FM https://websec.rea ...
- Web存储机制—sessionStorage,localStorage使用方法
Web存储机制,在这里主要聊有关于Web Storage API提供的存储机制,通过该机制,浏览器可以安全地存储键值对,比使用cookie更加直观.接下来简单的了解如何使用这方面的技术. 基本概念 W ...
- 分享一个.NET(C#)按指定字母个数截断英文字符串的方法–提供枚举选项,可保留完整单词
分享一个.NET(C#)按字母个数截断英文字符串的方法,该方法提供枚举选项.枚举选项包括:可保留完整单词,允许最后一个单词超过最大长度限制,字符串最后跟省略号以及不采取任何操作等,具体示例实现代码如下 ...
- C# PDF Page操作——设置页面切换按钮 C# 添加、读取Word脚注尾注 C#为什么不能像C/C++一样的支持函数只读传参 web 给大家分享一个好玩的东西,也许你那块就用的到
C# PDF Page操作——设置页面切换按钮 概述 在以下示例中,将介绍在PDF文档页面设置页面切换按钮的方法.示例中将页面切换按钮的添加分为了两种情况,一种是设置按钮跳转到首页.下页.上页或者 ...
- 分享一个解决MySQL写入中文乱码的方法
分享一个解决MySQL写入中文乱码的方法 之前有发帖请教过如何解决MySQL写入中文乱码的问题.但没人会,或者是会的人不想回答.搜索网上的答案并尝试很多次无效,所以当时就因为这个乱码问题搁浅了一个软件 ...
- 分享一个解析XML成为php数组的方法
原文:分享一个解析XML成为php数组的方法 <?php /* * To change this template, choose Tools | Templates * and open th ...
随机推荐
- CentOS配置SVN服务器
系统环境:CentOS系统:CentOS 6.5 1.检查是否安装了低版本的SVN rpm -qa subversion 2.卸载旧版本SVN yum remove subversion 3.安装SV ...
- PSP(11.24~11.30)
27号 类别c 内容c 开始时间s 结束e 中断I 净时间T 作业 构建执法.写博客 14:00 14:40 0m 40m 28号 类别c 内容c 开始时间s 结束e 中断I 净时间T java 编码 ...
- SpringMVC 自动封装枚举类的方法
springmvc默认无法自动封装枚举类,解决方法如下: 1.枚举类 public enum GoodsPromoteEnum { /** * 0 精品 */ fine("精品", ...
- mac-文本编辑器
windows时代最喜欢的文本编辑器一直是ultraedit,但到了mac下,破解的ultraedit退出时会异常,于是琢磨着换编辑器,最终选择了sublime text2,百度下载,不注册也可以用. ...
- system verilog中的类型转换(type casting)、位宽转换(size casting)和符号转换(sign casting)
类型转换 verilog中,任何类型的任何数值都用来给任何类型赋值.verilog使用赋值语句自动将一种类型的数值转换为另一种类型. 例如,当一个wire类型赋值给一个reg类型的变量时,wire类型 ...
- nginx日志分割脚本
[root@localhost nginx]# cat logs/nginx.pid 5118[root@localhost nginx]# kill -QUIT 5118-QUIT : 关闭进程-H ...
- Java基础(一) ---- 封装(Encapsulation)
- pkg-config
可以使用pkg-config获取的库需要有一个条件,那就是要求库的提供者,提供一个.pc文件.比如gtk+-2.0的pc文件内容如下: prefix=/usrexec_prefix=/usrlibdi ...
- LR12.53—第4课:准备Vuser脚本进行负载测试
第4课:准备Vuser脚本进行负载测试 在前面的课程中,您确认您的Vuser脚本的回放产生了真正的用户的精确仿真.下一个步骤是准备的脚本负载测试.如何将多用户系统同时工作的工作?会拖慢系统到不可接受的 ...
- python转exe的小工具
其实只是在cxfreeze的基础上加了个壳,做成窗口软件了 使用了pyqt做的界面,软件发布在了开源中国上,可以直接去下面的地址查看 http://git.oschina.net/robocky/py ...