首頁  >  文章  >  web前端  >  LocalStorage VS SessionStorage VS Cookie

LocalStorage VS SessionStorage VS Cookie

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-13 01:07:021047瀏覽

LocalStorage VS SessionStorage VS Cookie

Cookies LocalStorage SessionStorage
Capacity 4kb 5-10 MBs (Browser Dependent) 5 MBs
Accessibility All windows All windows Private to tab
Expiration Manually Set Never expires On tab close
Passed in request Yes No No
Storage Browser and Server Browser Only Browser Only

應用

正如您從上表中看到的主要區別。以下是每種儲存類型的應用:

  1. LocalStorage - 通常資料永遠不會過期,必須儲存非敏感數據,例如使用者首選項、應用程式狀態等。
  2. SessionStorage - 資料是選項卡私有的,一旦關閉視窗或選項卡就會過期。適合儲存僅在使用者導航單一標籤時需要保留的臨時資料(例如提交前的表單資料)。
  3. Cookie - 儲存容量非常小,伺服器可能需要數據,例如身份驗證令牌或使用者首選項。

句法

餅乾?

// below snippet will set username as key ?
// Johndoe as value ?
// will set expiry date for the cookie which is 31 Dec 2024
// path (cookie available to entire website)
// if no path specified then cookie will be available to that particular site which created that cookie
// you can delete the cookie by setting? the date that already expired (any previous date)
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";

讀取cookie

console.log(document.cookie) // Outputs all cookies? as a string

會話儲存?

sessionStorage.setItem('sessionData', 'temporaryValue');
let sessionData = sessionStorage.getItem('sessionData');
console.log(sessionData); // Outputs: temporaryValue

移除和清除

sessionStorage.removeItem('sessionData'); // it will only remove particular key
sessionStorage.clear(); // clean the whole storage

本地儲存?

最常用的儲存類型,所有功能都與會話類型類似。

//set item
localStorage.setItem('username', 'JohnDoe');
// get itme
let username = localStorage.getItem('username');
console.log(username); // Outputs: JohnDoe
// remove item with key-value
localStorage.removeItem('username');
// reset store
localStorage.clear();

領英? ❤

以上是LocalStorage VS SessionStorage VS Cookie的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn