三种浏览器存储方案,你还担心数据无处放吗

webStorage

基本概念

webStorage提供了两种存储方式,localStorage和sessionStorage。

  • localStorage是持久化存储,不主动删除存储的内容会永久存在
  • sessionStorage为会话级存储,关闭浏览器则销毁

具体的区别在于

  • 关闭网页后重新打开,localStorage会保留,sessionStorage不会被保留
  • 在页面内实现跳转,localStorage会保留,sessionStorage也会保留
  • 在页面外实现跳转(打开新网页),localStorage会保留,sessionStorage不会被保留
属性和方法

localStorage和sessionStorage都具有以下属性和方法

  • 设置值 setItem(key, value)
  • 通过索引获取值 key(index)
  • 通过key获取值 getItem(key)
  • 移除掉某个key removeItem(key)
  • 清空 clear()
  • length 存储数据的长度
localStorage.setItem('name', 'alice')
localStorage.setItem('age', 20)

通过开发者工具中的 Application 中 Storage 可以查看到存储的内容

因为locaStorage和sessionStorage是window上的属性,所以在Console控制台上也可以直接操作

工具封装

localStorage和sessionStorage只能存储字符串,当遇到对象时,会直接把它转成 “[Object Object]”这样的字符串,这样以后读取也只能读到“[Object Object]”,数据就会丢失

const lesson = {
  subject: "Math",
};
localStorage.setItem("lessonObj", lesson);
localStorage.setItem("lessonStr", JSON.stringify(lesson));

所以我们在存储对象时,需要先将对象转成字符串

每一次存储数据都要 stringify 将数据序列化,读取数据都需要 parse 解析成对象,可以将重复的代码进行封装,成为工具函数

class iceStore {
  constructor(flag) {
    this.storage = flag ? localStorage : sessionStorage;
  }
  setItem(key, value) {
    const str = JSON.stringify(value);
    this.storage.setItem(key, str);
  }
  getItem(key) {
    let value = this.storage.getItem(key);
    if (value) {
      return JSON.parse(value);
    }
  }
  key(index) {
    return this.storage.key(index);
  }
  removeItem(key) {
    return this.storage.removeItem(key);
  }
  clear() {
    return this.storage.clear();
  }
  length() {
    return this.storage.length;
  }
}
const localCache = new iceStore(true);
const sessionCache = new iceStore(false);
export { localCache, sessionCache };

在需要使用 localStorage/sessionStorage的地方引入即可~

indexedDB

indexedDB是用于客户端的数据库,使用键值对来保存大量的数据,有些像NoSQL。

通过以下代码先开启对于indexedDB的连接

// 打开名为iceDB的数据库,没有则新建一个
const dbRequest = indexedDB.open("iceDB")

// 第一次打开/版本更新时调用函数
dbRequest.onupgradeneeded = function(event){
    // 获取操作数据库的db对象
    const db = event.target.result
    // 创建一些存储对象,像表结构, keyPath 会作为表的主键,用于区分唯一性,
    // 存到users中的每一条数据需要有id属性
    db.createObjectStore("users", { keyPath: 'id' })
}

let db = null
dbRequest.onsuccess = function(event){
    // 拿到 db 对象,保存在全局,操作数据库用
    db = event.target.result
}

此时已经创建了名为iceDB的数据库,其中有一张表,名为user

// transaction中的第一个参数可以是数组,readwrite 可以读和写
const transaction = db.transaction("users", "readwrite")
// objectStore方法从上面的事务中拿到store对象
const store = transaction.objectStore("users")

// 增加
const request = store.add({ id: 1, name: 'kiki', 18})
// 一次操作完成的回调
request.onsuccess = function(){}
// 一次操作失败的回调
request.onerror = function(){}
// 事务全部完成,传入完成的回调
transaction.oncomplete = function(){}

// 查询,开启游标
const request = store.openCursor()
request.onsuccess = function(event){
    // event中包含游标,游标没有值的时候代表指到了最后
    const cursor = event.target.result
    if(cursor){
        // 在某个条件停止查询
        if(...){
           
        }else{
          // 游标继续查找 
          cursor.continue()
        }
    }
}

// 修改
// 先查询到指定的数据,通过游标直接改变数据
const value = cursor.value;
value.name = "lucy";
cursor.update(value)

// 删除
// 先查询到指定的数据,调用游标的删除方法
cursor.delete()

最终存储的效果

cookie虽然也是浏览器的存储方案,但一般由服务端通过http请求头 Set-Cookie 字段设置,浏览器端每次发送请求的时候都会携带

cookie的分类

  • 内存Cookie由浏览器维护,保存在内存中,浏览器关闭时Cookie就会销毁
  • 硬盘Cookie保存在硬盘中,有一个过期时间,用户手动清理或者过期时间到时,才会被清理

cookie设置过期时间

  • expires:设置的是Date.toUTCString()
  • max-age:设置过期的秒钟,例如一年为 60 * 60 * 24 * 365

cookie其它属性

  • domain 不指定,那么默认是 origin,不包括子域名,指定后包括子域名
  • path 指定主机下哪些路径可以接受cookie

图示如下

浏览器端设置cookie
通过 document.cookie 来设置,如果服务器端设置了 httpOnly,则浏览器端不可以更改服务器设置的cookie

具体的cookie设置方式可以参考这一篇服务器的文章~
如何通过cookie、session鉴权(nodejs/koa)

以上就是浏览器存储相关内容,关于js高级,还有很多需要开发者掌握的地方,可以看看我写的其他博文,持续更新中~

posted @ 2022-01-22 21:15  一颗冰淇淋  阅读(467)  评论(0编辑  收藏  举报