localStorage、sessionStorage、session和cookies有什么区别?
localStorage
、sessionStorage
、session 和 cookies
的技术优缺点是什么,我什么时候会使用其中一种?
What are the technical pros and cons of localStorage
, sessionStorage
, session and cookies
, and when would I use one over the other?
推荐答案
这是一个范围非常广泛的问题,很多优点/缺点将根据具体情况而定.
This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.
在所有情况下,这些存储机制将特定于单个计算机/设备上的单个浏览器.跨会话持续存储数据的任何要求都需要涉及您的应用程序服务器端 - 很可能使用数据库,但也可能使用 XML 或文本/CSV 文件.
In all cases, these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.
localStorage、sessionStorage 和 cookie 都是客户端存储解决方案.会话数据保存在您直接控制的服务器上.
localStorage, sessionStorage, and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.
localStorage 和 sessionStorage 是相对较新的 API(也就是说,并非所有旧版浏览器都支持它们)并且几乎相同(在 API 和功能方面),唯一的例外是持久性.sessionStorage(顾名思义)仅在浏览器会话期间可用(并在选项卡或窗口关闭时被删除)- 但是,它确实可以在页面重新加载后继续存在(来源 DOM 存储指南 - Mozilla 开发者网络).
localStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network).
显然,如果您存储的数据需要持续可用,那么 localStorage 比 sessionStorage 更可取 - 尽管您应该注意两者都可以由用户清除,因此您不应该依赖任何一个中的数据的持续存在案例.
Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.
localStorage 和 sessionStorage 非常适合在页面之间保存客户端脚本中所需的非敏感数据(例如:偏好、游戏分数).存储在 localStorage 和 sessionStorage 中的数据可以很容易地从客户端/浏览器中读取或更改,因此不应依赖于在应用程序中存储敏感或与安全相关的数据.
localStorage and sessionStorage are 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.
对于 cookie 也是如此,它们可以被用户轻易篡改,并且也可以以纯文本的形式从它们中读取数据 - 因此,如果您想要存储敏感数据,那么会话确实是您唯一的选择.如果您不使用 SSL,cookie 信息也可能在传输过程中被截获,尤其是在开放的 wifi 上.
This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then the session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.
从积极的方面来说,cookie 可以通过设置仅 HTTP 标志来防止跨站点脚本 (XSS)/脚本注入等安全风险,这意味着现代(支持)浏览器将阻止访问 cookie 和值来自 JavaScript(这也将阻止您自己的合法 JavaScript 访问它们).这对于身份验证 cookie 尤其重要,它用于存储包含登录用户详细信息的令牌 - 如果您有该 cookie 的副本,那么出于所有意图和目的,您成为该用户就 Web 应用程序而言,并且对用户拥有的数据和功能具有相同的访问权限.
On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.
由于 cookie 用于身份验证和用户数据的持久性,对于页面有效的 所有 cookie 将从浏览器发送到服务器,以用于每个对同一页面的请求域 - 这包括原始页面请求、任何后续 Ajax 请求、所有图像、样式表、脚本和字体.因此,不应使用 cookie 来存储大量信息.浏览器还可能对可存储在 cookie 中的信息大小施加限制.通常,cookie 用于存储用于身份验证、会话和广告跟踪的标识令牌.令牌本身通常不是人类可读的信息,而是链接到您的应用程序或数据库的加密标识符.
As cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain - this includes the original page request, any subsequent Ajax requests, all images, stylesheets, scripts, and fonts. For this reason, cookies should not be used to store large amounts of information. The browser may also impose limits on the size of information that can be stored in cookies. Typically cookies are used to store identifying tokens for authentication, session, and advertising tracking. The tokens are typically not human readable information in and of themselves, but encrypted identifiers linked to your application or database.
就功能而言,cookies、sessionStorage 和 localStorage 只允许您存储字符串 - 可以在设置时隐式转换原始值(这些在读取后需要转换回以用作它们的类型)但不能对象或数组(可以对它们进行 JSON 序列化以使用 API 存储它们).会话存储通常允许您存储服务器端语言/框架支持的任何原语或对象.
In terms of capabilities, cookies, sessionStorage, and localStorage only allow you to store strings - it is possible to implicitly convert primitive values when setting (these will need to be converted back to use them as their type after reading) but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.
由于 HTTP 是一种无状态协议 - Web 应用程序无法在返回网站时从以前的访问中识别用户 - 会话数据通常依赖于 cookie 令牌来识别用户以进行重复访问(尽管很少有 URL 参数可能用于相同目的).数据通常会有一个滑动到期时间(每次用户访问时都会更新),并且取决于您的服务器/框架,数据将要么存储在进程内(这意味着如果 Web 服务器崩溃或重新启动,数据将丢失)或外部存储在状态服务器或数据库.这在使用网络农场(给定网站的多个服务器)时也是必要的.
As HTTP is a stateless protocol - web applications have no way of identifying a user from previous visits on returning to the web site - session data usually relies on a cookie token to identify the user for repeat visits (although rarely URL parameters may be used for the same purpose). Data will usually have a sliding expiry time (renewed each time the user visits), and depending on your server/framework data will either be stored in-process (meaning data will be lost if the web server crashes or is restarted) or externally in a state server or database. This is also necessary when using a web-farm (more than one server for a given website).
由于会话数据完全由您的应用程序(服务器端)控制,因此对于本质上敏感或安全的事物来说,它是最好的地方.
As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.
服务器端数据的明显缺点是可伸缩性 - 在会话期间每个用户都需要服务器资源,并且客户端所需的任何数据都必须随每个请求一起发送.由于服务器无法知道用户是否导航到另一个站点或关闭其浏览器,因此会话数据必须在给定时间后过期,以避免所有服务器资源被废弃的会话占用.因此,在使用会话数据时,您应该注意数据过期和丢失的可能性,尤其是在表单较长的页面上.如果用户删除他们的 cookie 或切换浏览器/设备,它也会丢失.
The obvious disadvantage of server-side data is scalability - server resources are required for each user for the duration of the session, and that any data needed client side must be sent with each request. As the server has no way of knowing if a user navigates to another site or closes their browser, session data must expire after a given time to avoid all server resources being taken up by abandoned sessions. When using session data you should, therefore, be aware of the possibility that data will have expired and been lost, especially on pages with long forms. It will also be lost if the user deletes their cookies or switches browsers/devices.
一些 Web 框架/开发人员使用隐藏的 HTML 输入将数据从表单的一个页面保存到另一个页面以避免会话过期.
Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.
localStorage、sessionStorage 和 cookie 都受制于同源"规则,这意味着浏览器应阻止访问数据,但设置信息开始的域除外.
localStorage, sessionStorage, and cookies are all subject to "same-origin" rules which means browsers should prevent access to the data except the domain that set the information to start with.
如需进一步了解客户端存储技术,请参阅深入了解 Html 5.
For further reading on client storage technologies see Dive Into Html 5.
相关文章