昨天談完Cookie 🍪 ,今天我們把剩下的儲存機制說完(LocalStorage、SessionStorage、IndexedDB)
用來存放大量、不會過期的資料
// 儲存
localStorage.setItem("theme", "dark");
// 讀取
console.log(localStorage.getItem("theme")); // "dark"
// 刪除
localStorage.removeItem("theme");
你可以在開發者工具 → 應用程式 → 本機儲存空間裡看到,每一筆資料是以Key-Value形式儲存
用來儲存只在瀏覽器分頁存活的資料
// 儲存
sessionStorage.setItem("step", "2");
// 讀取
console.log(sessionStorage.getItem("step")); // "2"
// 刪除
sessionStorage.clear();
可以在開發者工具 → 應用程式 → 工作階段儲存空間看到,也是以 Key-Value 形式儲存:
IsThisFirstTime_Log_From_LiveServer是因為我用VS Code的Live Server開啟的
Note:
LocalStorage 和 SessionStorage很像,他們不一樣的地方在於:
瀏覽器內建的 NoSQL 資料庫,可以存放結構化資料
let request = indexedDB.open("MyDB", 1);
request.onsuccess = function(event) {
console.log("Database Opened !");
};
request.onupgradeneeded = function(event) {
let db = event.target.result;
db.createObjectStore("users", { keyPath: "id" });
};
特性 | Cookie | LocalStorage | SessionStorage | IndexedDB |
---|---|---|---|---|
容量 | ~4KB | ~5MB | ~5MB | 100MB 以上 |
到期時間 | 可設定 / 預設關閉刪除 | 永久 | 關閉分頁刪除 | 永久 |
自動附在 HTTP 請求 | ✓ | X | X | X |
儲存資料類型 | 字串 | 字串 | 字串 | 結構化資料 |
常見用途 | 登入狀態、追蹤 | 偏好設定、離線資料 | 單次暫存資料 | 離線應用、大量資料 |
⚠️ 注意:重要資料不要存在用戶端,尤其不要明碼儲存敏感資訊
不論哪一種儲存方式,都要搭配伺服器驗證與安全策略,避免被竊取
https://miahsuwork.medium.com/第八週-網頁資料儲存-cookie-local-storage-session-storage-a3f40013da37
https://ithelp.ithome.com.tw/articles/10268532
https://vocus.cc/article/6583dcbbfd89780001edd0ab
https://web.dev/articles/indexeddb?hl=zh-tw
https://www.explainthis.io/zh-hant/swe/what-is-indexeddb