LiuL0703 / LiuL0703.github.io

Blog

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cookie, LocalStorage 与 SessionStorage

LiuL0703 opened this issue · comments

特点 Cookie LocalStorage sessionStorage
存放数据大小 4k左右 一般为5M
存放周期 一般由服务器生成,可人为设置失效时间。如果在浏览器端生成,默认是关闭浏览器后失效 除非被清除,否则永久保存 仅在当前会话下有效,关闭页面或浏览器后被清除
与服务器端通信 每次都携带在HTTP请求头中 仅在客户端中保存不参与服务器通信
概念 是服务器发送到用户浏览器并保存在浏览器上的一块数据,它会在浏览器下一次发起请求时被携带并发送到服务器上。比较经典的,可以它用来确定两次请求是否来自于同一个浏览器,从而能够确认和保持用户的登录状态。Cookie的使用使得基于无状态的HTTP协议上记录稳定的状态信息成为了可能 没有时间限制的数据存储 (持久化) 针对一个 session 的数据存储,当用户关闭浏览器窗口后(不包括重载),数据会被删除。
用途 1.会话状态管理(如用户登录状态、购物车) 2.个性化设置(如用户自定义设置) 3.浏览器行为跟踪(如跟踪分析用户行为) 用于本地存储数据❶ 可以将一部分数据在当前会话中保存下来,刷新页面数据依旧存在。但当页面关闭后,sessionStorage 中的数据就会被清空可以用来存储比较重要的数据 安全性高于cookie❶
缺陷 1.cookie会被加在每个http请求中 增加了流量 2. cookie以明文传递有安全问题 3.存储大小限制 It works on same-origin policy. So, data stored will only be available on the same origin.(受同源策略的影响 数据只能在同源网站内存储和使用) 1. The data is available only inside the window/tab in which it was set.(数据只在当前网页中有效) 2. The data is not persistent i.e. it will be lost once the window/tab is closed.(数据不能持续保存 关闭网页或浏览器后数据丢失) 3. Like localStorage, tt works on same-origin policy. So, data stored will only be available on the same origin(和localStorage类似 受同源策略影响 数据只在符合同源策略的网页中使用)
相同点 localStorage, sessionStorage and cookies are all subject to "same-origin" rules which means browsers should prevent access to the data except from the domain that set the information to start with.
❶: perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security related data within applications.