QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

手机号码,快捷登录

泡泡马甲APP 更多内容请下载泡泡马甲手机客户端APP 立即下载 ×
查看: 2827|回复: 0

[HTML/CSS/JS] 你还在直接用 localStorage 么?该提升下逼格了

[复制链接]

等级头衔

积分成就    金币 : 2802
   泡泡 : 1516
   精华 : 6
   在线时间 : 1242 小时
   最后登录 : 2024-4-28

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老

联系方式
发表于 2022-7-2 17:44:52 | 显示全部楼层 |阅读模式
       很多人在用 localStorage 或 sessionStorage 的时候喜欢直接用,明文存储,直接将信息暴露在;浏览器中,虽然一般场景下都能应付得了且简单粗暴,但特殊需求情况下,比如设置定时功能,就不能实现。就需要对其进行二次封装,为了在使用上增加些安全感,那加密也必然是少不了的了。为方便项目使用,特对常规操作进行封装。2 d& e/ S4 m# j& v9 f- u, M9 |9 L1 L
设计
# J3 n5 ]: Y. J  B  k       封装之前先梳理下所需功能,并要做成什么样,采用什么样的规范,部分主要代码片段是以 localStorage作为示例,最后会贴出完整代码的。可以结合项目自行优化,也可以直接使用。( v8 G, {2 t- h6 d" ?( F( c: U
  1. // 区分存储类型 type
  2. // 自定义名称前缀 prefix
  3. // 支持设置过期时间 expire
  4. // 支持加密可选,开发环境下未方便调试可关闭加密
  5. // 支持数据加密 这里采用 crypto-js 加密 也可使用其他方式
  6. // 判断是否支持 Storage isSupportStorage
  7. // 设置 setStorage
  8. // 获取 getStorage
  9. // 是否存在 hasStorage
  10. // 获取所有key getStorageKeys
  11. // 根据索引获取key getStorageForIndex
  12. // 获取localStorage长度 getStorageLength
  13. // 获取全部 getAllStorage
  14. // 删除 removeStorage
  15. // 清空 clearStorage
  16. //定义参数 类型 window.localStorage,window.sessionStorage,
  17. const config = {
  18.     type: 'localStorage', // 本地存储类型 localStorage/sessionStorage
  19.     prefix: 'SDF_0.0.1', // 名称前缀 建议:项目名 + 项目版本
  20.     expire: 1, //过期时间 单位:秒
  21.     isEncrypt: true // 默认加密 为了调试方便, 开发过程中可以不加密
  22. }
设置 setStorage
- v0 e0 o8 e! Z       Storage 本身是不支持过期时间设置的,要支持设置过期时间,可以效仿 Cookie 的做法,setStorage(key,value,expire) 方法,接收三个参数,第三个参数就是设置过期时间的,用相对时间,单位秒,要对所传参数进行类型检查。可以设置统一的过期时间,也可以对单个值得过期时间进行单独配置。两种方式按需配置。
$ N: X- n8 A- _6 g* P& W" W7 p代码实现:
8 Y$ }5 u4 [- H  z3 N' E3 r/ S
  1. // 设置 setStorage
  2. export const setStorage = (key,value,expire=0) => {
  3.     if (value === '' || value === null || value === undefined) {
  4.         value = null;
  5.     }
  6.     if (isNaN(expire) || expire < 1) throw new Error("Expire must be a number");
  7.     expire = (expire?expire:config.expire) * 60000;
  8.     let data = {
  9.         value: value, // 存储值
  10.         time: Date.now(), //存值时间戳
  11.         expire: expire // 过期时间
  12.     }
  13.     window[config.type].setItem(key, JSON.stringify(data));
  14. }
获取 getStorage
% A8 k* o! o% J6 ]1 R       首先要对 key 是否存在进行判断,防止获取不存在的值而报错。对获取方法进一步扩展,只要在有效期内获取 Storage 值,就对过期时间进行续期,如果过期则直接删除该值。并返回 null& |8 D, I5 |; p1 ]8 \5 C, L* `
  1. // 获取 getStorage
  2. export const getStorage = (key) => {
  3.     // key 不存在判断
  4.     if (!window[config.type].getItem(key) || JSON.stringify(window[config.type].getItem(key)) === 'null'){
  5.         return null;
  6.     }
  7.     // 优化 持续使用中续期
  8.     const storage = JSON.parse(window[config.type].getItem(key));
  9.     console.log(storage)
  10.     let nowTime = Date.now();
  11.     console.log(config.expire*6000 ,(nowTime - storage.time))
  12.     // 过期删除
  13.     if (storage.expire && config.expire*6000 < (nowTime - storage.time)) {
  14.         removeStorage(key);
  15.         return null;
  16.     } else {
  17.         // 未过期期间被调用 则自动续期 进行保活
  18.         setStorage(key,storage.value);
  19.         return storage.value;
  20.     }
  21. }
获取所有值6 @+ R! n9 s9 O+ \) Z, n
  1. // 获取全部 getAllStorage
  2. export const getAllStorage = () => {
  3.     let len = window[config.type].length // 获取长度
  4.     let arr = new Array() // 定义数据集
  5.     for (let i = 0; i < len; i++) {
  6.         // 获取key 索引从0开始
  7.         let getKey = window[config.type].key(i)
  8.         // 获取key对应的值
  9.         let getVal = window[config.type].getItem(getKey)
  10.         // 放进数组
  11.         arr[i] = { 'key': getKey, 'val': getVal, }
  12.     }
  13.     return arr
  14. }
删除 removeStorage
( m1 T  F9 M( a8 q
  1. // 名称前自动添加前缀
  2. const autoAddPrefix = (key) => {
  3.     const prefix = config.prefix ? config.prefix + '_' : '';
  4.     return  prefix + key;
  5. }
  6. // 删除 removeStorage
  7. export const removeStorage = (key) => {
  8.     window[config.type].removeItem(autoAddPrefix(key));
  9. }
清空 clearStorage
  X" E! X" s6 n/ S* N9 K$ ^2 M
  1. // 清空 clearStorage
  2. export const clearStorage = () => {
  3.     window[config.type].clear();
  4. }
加密、解密
1 b& p* }( m( ?, E       加密采用的是 crypto-js
9 F6 ~8 ?/ e2 T
  1. // 安装crypto-js
  2. npm install crypto-js
  3. // 引入 crypto-js 有以下两种方式
  4. import CryptoJS from "crypto-js";
  5. // 或者
  6. const CryptoJS = require("crypto-js");
      对 crypto-js 设置密钥和密钥偏移量,可以采用将一个私钥经 MD5 加密生成16位密钥获得。
! H" ?# I0 c5 G! X5 A4 e
  1. // 十六位十六进制数作为密钥
  2. const SECRET_KEY = CryptoJS.enc.Utf8.parse("3333e6e143439161");
  3. // 十六位十六进制数作为密钥偏移量
  4. const SECRET_IV = CryptoJS.enc.Utf8.parse("e3bbe7e3ba84431a");
      对加密方法进行封装9 P; c1 S- n) s( h1 W6 v3 K
  1. /**
  2. * 加密方法
  3. * @param data
  4. * @returns {string}
  5. */
  6. export function encrypt(data) {
  7.   if (typeof data === "object") {
  8.     try {
  9.       data = JSON.stringify(data);
  10.     } catch (error) {
  11.       console.log("encrypt error:", error);
  12.     }
  13.   }
  14.   const dataHex = CryptoJS.enc.Utf8.parse(data);
  15.   const encrypted = CryptoJS.AES.encrypt(dataHex, SECRET_KEY, {
  16.     iv: SECRET_IV,
  17.     mode: CryptoJS.mode.CBC,
  18.     padding: CryptoJS.pad.Pkcs7
  19.   });
  20.   return encrypted.ciphertext.toString();
  21. }
      对解密方法进行封装1 l4 ^4 L2 b2 C& G* f/ N
  1. /**
  2. * 解密方法
  3. * @param data
  4. * @returns {string}
  5. */
  6. export function decrypt(data) {
  7.   const encryptedHexStr = CryptoJS.enc.Hex.parse(data);
  8.   const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  9.   const decrypt = CryptoJS.AES.decrypt(str, SECRET_KEY, {
  10.     iv: SECRET_IV,
  11.     mode: CryptoJS.mode.CBC,
  12.     padding: CryptoJS.pad.Pkcs7
  13.   });
  14.   const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  15.   return decryptedStr.toString();
  16. }
在存储数据及获取数据中进行使用:) _; W2 D4 z% C" A) e. a
       这里我们主要看下进行加密和解密部分,部分方法在下面代码段中并未展示,请注意,不能直接运行。
  E" F6 P. f# o5 e$ D8 X8 L
  1. const config = {
  2.     type: 'localStorage', // 本地存储类型 sessionStorage
  3.     prefix: 'SDF_0.0.1', // 名称前缀 建议:项目名 + 项目版本
  4.     expire: 1, //过期时间 单位:秒
  5.     isEncrypt: true // 默认加密 为了调试方便, 开发过程中可以不加密
  6. }
  7. // 设置 setStorage
  8. export const setStorage = (key, value, expire = 0) => {
  9.     if (value === '' || value === null || value === undefined) {
  10.         value = null;
  11.     }
  12.     if (isNaN(expire) || expire < 0) throw new Error("Expire must be a number");
  13.     expire = (expire ? expire : config.expire) * 1000;
  14.     let data = {
  15.         value: value, // 存储值
  16.         time: Date.now(), //存值时间戳
  17.         expire: expire // 过期时间
  18.     }
  19.     // 对存储数据进行加密 加密为可选配置
  20.     const encryptString = config.isEncrypt ? encrypt(JSON.stringify(data)): JSON.stringify(data);
  21.     window[config.type].setItem(autoAddPrefix(key), encryptString);
  22. }
  23. // 获取 getStorage
  24. export const getStorage = (key) => {
  25.     key = autoAddPrefix(key);
  26.     // key 不存在判断
  27.     if (!window[config.type].getItem(key) || JSON.stringify(window[config.type].getItem(key)) === 'null') {
  28.         return null;
  29.     }
  30.     // 对存储数据进行解密
  31.     const storage = config.isEncrypt ? JSON.parse(decrypt(window[config.type].getItem(key))) : JSON.parse(window[config.type].getItem(key));
  32.     let nowTime = Date.now();
  33.    
  34.     // 过期删除
  35.     if (storage.expire && config.expire * 6000 < (nowTime - storage.time)) {
  36.         removeStorage(key);
  37.         return null;
  38.     } else {
  39.         //  持续使用时会自动续期
  40.         setStorage(autoRemovePrefix(key), storage.value);
  41.         return storage.value;
  42.     }
  43. }
使用
& h" Y7 c( \$ I' k( Q* t; ?       使用的时候你可以通过 import 按需引入,也可以挂载到全局上使用,一般建议少用全局方式或全局变量,为后来接手项目继续开发维护的人,追查代码留条便捷之路!不要为了封装而封装,尽可能基于项目需求和后续的通用,以及使用上的便捷。比如获取全部存储变量,如果你项目上都未曾用到过,倒不如删减掉,留着过年也不见得有多香,不如为减小体积做点贡献!
" L, A& Z& n- o  O. m( \
  1. import {isSupportStorage, hasStorage, setStorage,getStorage,getStorageKeys,getStorageForIndex,getStorageLength,removeStorage,getStorageAll,clearStorage} from '@/utils/storage'
完整代码# z; e4 f: i, \* u
       该代码已进一步完善,需要的可以直接进一步优化,也可以将可优化或可扩展的建议,留言说明,我会进一步迭代的。可以根据自己的需要删除一些不用的方法,以减小文件大小。
8 |8 j* l. M# j
  1. /***
  2. * title: storage.js
  3. * Desc: 对存储的简单封装
  4. */
  5. import CryptoJS from 'crypto-js';
  6. // 十六位十六进制数作为密钥
  7. const SECRET_KEY = CryptoJS.enc.Utf8.parse("3333e6e143439161");
  8. // 十六位十六进制数作为密钥偏移量
  9. const SECRET_IV = CryptoJS.enc.Utf8.parse("e3bbe7e3ba84431a");
  10. // 类型 window.localStorage,window.sessionStorage,
  11. const config = {
  12.     type: 'localStorage', // 本地存储类型 sessionStorage
  13.     prefix: 'SDF_0.0.1', // 名称前缀 建议:项目名 + 项目版本
  14.     expire: 1, //过期时间 单位:秒
  15.     isEncrypt: true // 默认加密 为了调试方便, 开发过程中可以不加密
  16. }
  17. // 判断是否支持 Storage
  18. export const isSupportStorage = () => {
  19.     return (typeof (Storage) !== "undefined") ? true : false
  20. }
  21. // 设置 setStorage
  22. export const setStorage = (key, value, expire = 0) => {
  23.     if (value === '' || value === null || value === undefined) {
  24.         value = null;
  25.     }
  26.     if (isNaN(expire) || expire < 0) throw new Error("Expire must be a number");
  27.     expire = (expire ? expire : config.expire) * 1000;
  28.     let data = {
  29.         value: value, // 存储值
  30.         time: Date.now(), //存值时间戳
  31.         expire: expire // 过期时间
  32.     }
  33.    
  34.     const encryptString = config.isEncrypt
  35.     ? encrypt(JSON.stringify(data))
  36.     : JSON.stringify(data);
  37.    
  38.     window[config.type].setItem(autoAddPrefix(key), encryptString);
  39. }
  40. // 获取 getStorage
  41. export const getStorage = (key) => {
  42.     key = autoAddPrefix(key);
  43.     // key 不存在判断
  44.     if (!window[config.type].getItem(key) || JSON.stringify(window[config.type].getItem(key)) === 'null') {
  45.         return null;
  46.     }
  47.     // 优化 持续使用中续期
  48.     const storage = config.isEncrypt
  49.     ? JSON.parse(decrypt(window[config.type].getItem(key)))
  50.     : JSON.parse(window[config.type].getItem(key));
  51.    
  52.     let nowTime = Date.now();
  53.     // 过期删除
  54.     if (storage.expire && config.expire * 6000 < (nowTime - storage.time)) {
  55.         removeStorage(key);
  56.         return null;
  57.     } else {
  58.         // 未过期期间被调用 则自动续期 进行保活
  59.         setStorage(autoRemovePrefix(key), storage.value);
  60.         return storage.value;
  61.     }
  62. }
  63. // 是否存在 hasStorage
  64. export const hasStorage = (key) => {
  65.     key = autoAddPrefix(key);
  66.     let arr = getStorageAll().filter((item)=>{
  67.         return item.key === key;
  68.     })
  69.     return arr.length ? true : false;
  70. }
  71. // 获取所有key
  72. export const getStorageKeys = () => {
  73.     let items = getStorageAll()
  74.     let keys = []
  75.     for (let index = 0; index < items.length; index++) {
  76.         keys.push(items[index].key)
  77.     }
  78.     return keys
  79. }
  80. // 根据索引获取key
  81. export const getStorageForIndex = (index) => {
  82.     return window[config.type].key(index)
  83. }
  84. // 获取localStorage长度
  85. export const getStorageLength = () => {
  86.     return window[config.type].length
  87. }
  88. // 获取全部 getAllStorage
  89. export const getStorageAll = () => {
  90.     let len = window[config.type].length // 获取长度
  91.     let arr = new Array() // 定义数据集
  92.     for (let i = 0; i < len; i++) {
  93.         // 获取key 索引从0开始
  94.         let getKey = window[config.type].key(i)
  95.         // 获取key对应的值
  96.         let getVal = window[config.type].getItem(getKey)
  97.         // 放进数组
  98.         arr[i] = {'key': getKey, 'val': getVal,}
  99.     }
  100.     return arr
  101. }
  102. // 删除 removeStorage
  103. export const removeStorage = (key) => {
  104.     window[config.type].removeItem(autoAddPrefix(key));
  105. }
  106. // 清空 clearStorage
  107. export const clearStorage = () => {
  108.     window[config.type].clear();
  109. }
  110. // 名称前自动添加前缀
  111. const autoAddPrefix = (key) => {
  112.     const prefix = config.prefix ? config.prefix + '_' : '';
  113.     return  prefix + key;
  114. }
  115. // 移除已添加的前缀
  116. const autoRemovePrefix = (key) => {
  117.     const len = config.prefix ? config.prefix.length+1 : '';
  118.     return key.substr(len)
  119.     // const prefix = config.prefix ? config.prefix + '_' : '';
  120.     // return  prefix + key;
  121. }
  122. /**
  123. * 加密方法
  124. * @param data
  125. * @returns {string}
  126. */
  127. const encrypt = (data) => {
  128.     if (typeof data === "object") {
  129.         try {
  130.             data = JSON.stringify(data);
  131.         } catch (error) {
  132.             console.log("encrypt error:", error);
  133.         }
  134.     }
  135.     const dataHex = CryptoJS.enc.Utf8.parse(data);
  136.     const encrypted = CryptoJS.AES.encrypt(dataHex, SECRET_KEY, {
  137.         iv: SECRET_IV,
  138.         mode: CryptoJS.mode.CBC,
  139.         padding: CryptoJS.pad.Pkcs7
  140.     });
  141.     return encrypted.ciphertext.toString();
  142. }
  143. /**
  144. * 解密方法
  145. * @param data
  146. * @returns {string}
  147. */
  148. const decrypt = (data) => {
  149.     const encryptedHexStr = CryptoJS.enc.Hex.parse(data);
  150.     const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  151.     const decrypt = CryptoJS.AES.decrypt(str, SECRET_KEY, {
  152.         iv: SECRET_IV,
  153.         mode: CryptoJS.mode.CBC,
  154.         padding: CryptoJS.pad.Pkcs7
  155.     });
  156.     const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  157.     return decryptedStr.toString();
  158. }
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号 )

GMT+8, 2024-4-28 19:31

Powered by paopaomj X3.4 © 2016-2024 sitemap

快速回复 返回顶部 返回列表