动态

详情 返回 返回

三種瀏覽器存儲方案,你還擔心數據無處放嗎 - 动态 详情

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

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高級,還有很多需要開發者掌握的地方,可以看看我寫的其他博文,持續更新中~

user avatar yinzhixiaxue 头像 vleedesigntheory 头像 zohocrm 头像 minghuajiwu 头像 jueqiangdeqianbi 头像
点赞 5 用户, 点赞了这篇动态!
点赞

Add a new 评论

Some HTML is okay.