localStorage、sessionStorage、session和cookie的技术优缺点是什么,什么时候使用其中一个而不是另一个?


当前回答

LocalStorage:

Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. Available size is 5MB which considerably more space to work with than a typical 4KB cookie. The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server. The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site. It works on same-origin policy. So, data stored will only be available on the same origin.

饼干:

我们可以为每个cookie设置过期时间 4K的限制适用于整个cookie,包括名称、值、有效期等。为了支持大多数浏览器,请将名称保持在4000字节以下,并且cookie的总体大小保持在4093字节以下。 对于每个HTTP请求(HTML、图像、JavaScript、CSS等),数据都被发送回服务器,这增加了客户端和服务器之间的流量。

sessionStorage:

It is similar to localStorage. Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted The data is available only inside the window/tab in which it was set. The data is not persistent i.e. it will be lost once the window/tab is closed. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

其他回答

好吧,LocalStorage,因为它被称为你的浏览器的本地存储,它可以节省高达10MB, SessionStorage也一样,但正如它的名字所说,它是基于会话的,关闭浏览器后将被删除,也可以节省比LocalStorage更少的数据,比如最多5MB,但cookie是非常小的数据存储在你的浏览器中,可以节省4KB,可以通过服务器或浏览器访问…

我还创建了下面的图像来显示差异:

这是一个非常宽泛的问题,很多优点和缺点都要根据具体情况而定。

在所有情况下,这些存储机制将特定于单个计算机/设备上的单个浏览器。任何跨会话持续存储数据的需求都需要应用程序服务器端参与—很可能使用数据库,但也可能使用XML或文本/CSV文件。

localStorage、sessionStorage和cookies都是客户端存储解决方案。会话数据保存在服务器上,由您直接控制。

localStorage和sessionStorage

localStorage和sessionStorage是相对较新的api(也就是说,并不是所有的旧浏览器都支持它们),除了持久性之外,它们在api和功能上几乎相同。sessionStorage(顾名思义)仅在浏览器会话期间可用(并且在选项卡或窗口关闭时被删除)-但是,它在页面重新加载时仍然有效(源DOM存储指南- Mozilla Developer Network)。

显然,如果您所存储的数据需要持续可用,那么localStorage比sessionStorage更可取——尽管您应该注意,两者都可以由用户清除,所以您不应该依赖于数据的持续存在。

localStorage和sessionStorage非常适合在页面之间持久化客户端脚本所需的非敏感数据(例如:偏好、游戏分数)。存储在localStorage和sessionStorage中的数据可以很容易地从客户端/浏览器中读取或更改,因此不应该依赖于在应用程序中存储敏感或与安全相关的数据。

饼干

cookie也是如此,用户可以对其进行简单的篡改,数据也可以以纯文本的形式从cookie中读取——因此,如果您想存储敏感数据,那么会话确实是您的唯一选择。如果您没有使用SSL, cookie信息也可能在传输过程中被拦截,特别是在开放的wifi上。

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.

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.

localStorage vs. sessionStorage vs. Cookies

在功能方面,cookie, sessionStorage和localStorage只允许你存储字符串-它可以在设置时隐式转换原始值(这些将需要在读取后转换回使用它们作为它们的类型),但不允许对象或数组(可以使用JSON序列化它们来使用api存储它们)。会话存储通常允许您存储服务器端语言/框架支持的任何原语或对象。

客户端与服务器端

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).

由于会话数据完全由应用程序(服务器端)控制,因此它是保存敏感或安全数据的最佳位置。

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输入将数据从表单的一个页面保存到另一个页面,以避免会话过期。

localStorage、sessionStorage和cookie都遵循“同源”规则,这意味着浏览器应该阻止访问除设置信息起始域之外的数据。

有关客户端存储技术的进一步阅读,请参阅Html 5。

这里是一个快速的回顾和简单而快速的理解

来自freecodecamp的Beau Carnes教练

Web Storage API提供了一种机制,通过这种机制,浏览器可以安全地存储键/值对,这比使用cookie要直观得多。 Web Storage API用两个新的属性扩展了Window对象——Window。sessionStorage和Window.localStorage。-调用其中一个将创建Storage对象的实例,通过该实例可以设置、检索和删除数据项。每个源(域)的sessionStorage和localStorage使用不同的存储对象。

存储对象是简单的键值存储,类似于对象,但是它们在页面加载时保持不变。

localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting', '#a4509b');

键和值总是字符串。要存储任何类型,将其转换为字符串,然后存储它。总是建议使用Storage接口方法。

var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('Converting String to Object: ', JSON.parse(retrievedObject));

Web Storage中的两种机制如下:

sessionStorage为每个给定的originSame-origin策略维护一个单独的存储区域,该策略在页面会话期间可用(只要浏览器处于打开状态,包括页面重新加载和恢复)。 localStorage做同样的事情,但是即使浏览器关闭并重新打开,它仍然存在。

存储«本地存储将数据写入磁盘,而会话存储仅将数据写入内存。当你的应用程序退出时,任何写入会话存储的数据都会被清除。

可用的最大存储空间因浏览器而异,但大多数浏览器至少实现了w3c推荐的最大存储空间限制5MB。

+----------------+--------+---------+-----------+--------+
|                | Chrome | Firefox | Safari    |  IE    |
+----------------+--------+---------+-----------+--------+
| LocalStorage   | 10MB   | 10MB    | 5MB       | 10MB   |
+----------------+--------+---------+-----------+--------+
| SessionStorage | 10MB   | 10MB    | Unlimited | 10MB   |
+----------------+--------+---------+-----------+--------+

总是捕获LocalStorage安全和配额超过错误

QuotaExceededError: When storage limits exceeds on this function window.sessionStorage.setItem(key, value);, it throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.) DOMException.QUOTA_EXCEEDED_ERR is 22, example fiddle. SecurityError : Uncaught SecurityError: Access to 'localStorage' is denied for this document. CHROME:-Privacy and security « Content settings « Cookies « Block third-party cookies.

StorageEvent«当存储区域发生变化时,存储事件在文档的Window对象上触发。当用户代理要为Document发送存储通知时,用户代理必须将任务排队,以便使用StorageEvent在Document对象的Window对象上触发名为storage的事件。

注意:有关真实世界的示例,请参见Web Storage Demo。查看源代码

监听dom/Window上的存储事件,以捕捉存储中的变化。小提琴。


cookie (web cookie,浏览器cookie) cookie是数据,以名称-值对的形式存储在计算机上的小文本文件中。

使用Document.cookie访问JavaScript

还可以使用Document通过JavaScript创建新的cookie。如果没有设置HttpOnly标志,现有的cookie也可以从JavaScript访问。

document.cookie = "yummy_cookie=choco"; 
document.cookie = "tasty_cookie=strawberry"; 
console.log(document.cookie); 
// logs "yummy_cookie=choco; tasty_cookie=strawberry"

Secure and HttpOnly cookie HTTP状态管理机制

在web应用程序中,cookie通常用于识别用户及其经过认证的会话

当接收到HTTP请求时,服务器可以发送一个Set-Cookie报头和响应。cookie通常由浏览器存储,然后在cookie HTTP报头中与向同一服务器发出的请求一起发送。

Set-Cookie: <cookie-name>=<cookie-value> 
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>

当客户端关闭时,会话cookie将被删除。它们没有指定Expires或Max-Age指令。

Set-Cookie: sessionid=38afes7a8; HttpOnly; Path=/

永久cookie在特定日期(Expires)或特定时间长度(Max-Age)后过期。

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly

Cookie HTTP请求头包含存储的HTTP Cookie,之前由服务器通过Set-Cookie头发送。只有http的cookie不能通过JavaScript通过文档访问。cookie属性,XMLHttpRequest和Request api,以减轻对跨站脚本(XSS)的攻击。

cookie主要用于以下三个目的:

Session management « Logins, shopping carts, game scores, or anything else the server should remember Personalization « User preferences, themes, and other settings Tracking (Recording and analyzing user behavior) « Cookies have a domain associated to them. If this domain is the same as the domain of the page you are on, the cookies is said to be a first-party cookie. If the domain is different, it is said to be a third-party cookie. While first-party cookies are sent only to the server setting them, a web page may contain images or other components stored on servers in other domains (like ad banners). Cookies that are sent through these third-party components are called third-party cookies and are mainly used for advertising and tracking across the web.

cookie的发明是为了解决“如何记住用户的信息”的问题:

当用户访问一个网页时,他的名字可以存储在一个cookie中。 用户下次访问该页时,属于该页的cookie将被添加到请求中。通过这种方式,服务器获得必要的数据来“记住”有关用户的信息。

GitHubGist例子


作为总结,

localStorage persists over different tabs or windows, and even if we close the browser, accordingly with the domain security policy and user choices about quota limit. sessionStorage object does not persist if we close the tab (top-level browsing context) as it does not exists if we surf via another tab or window. Web Storage (session, local) allows us to save a large amount of key/value pairs and lots of text, something impossible to do via cookie. Cookies that are used for sensitive actions should have a short lifetime only. Cookies mainly used for advertising and tracking across the web. See for example the types of cookies used by Google. Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web storage API (localStorage and sessionStorage) and IndexedDB.

localStorage

存储在localStorage中的数据没有过期日期,只能通过JavaScript或清除浏览器缓存/本地存储的数据来清除。 存储限制是三者中最大的。 存储在localStorage中的数据将一直存在,直到显式删除为止。所做的更改将被保存,并可用于当前和将来对站点的所有访问。 它在同源策略上工作。因此,存储的数据只能在相同的原点上可用。

sessionStorage

它仅为会话存储数据,这意味着数据将一直存储到浏览器(或选项卡)关闭为止。 数据从不传输到服务器。 更改仅适用于每个窗口(或Chrome和Firefox等浏览器中的选项卡)。所做的更改将被保存,并可用于当前页面,以及在同一窗口上对该网站的未来访问。一旦窗口关闭,存储就会被删除。