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

LocalStorage VS SessionStorage VS Cookie

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-11-13 01:07:021048浏览

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