Html localStorage、sessionStorage、session 和 cookie 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19867599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 15:11:06  来源:igfitidea点击:

What is the difference between localStorage, sessionStorage, session and cookies?

htmlcookieslocal-storagesession-storage

提问by Pank

What are the technical pros and cons of localStorage, sessionStorage, session and cookies, and when would I use one over the other?

localStorage、sessionStorage、session 和 cookie 的技术优缺点是什么,我什么时候应该使用其中一种?

回答by pwdst

This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.

这是一个范围极其广泛的问题,许多优点/缺点都与具体情况有关。

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.

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

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 和 cookie 都是客户端存储解决方案。会话数据保存在您直接控制的服务器上。

localStorage and sessionStorage

localStorage 和 sessionStorage

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 是相对较新的 API(意思是,并非所有旧版浏览器都支持它们)并且几乎相同(在 API 和功能方面),唯一的例外是持久性。sessionStorage(顾名思义)仅在浏览器会话期间可用(并在选项卡或窗口关闭时被删除) - 但是,它可以在页面重新加载后继续存在(源DOM 存储指南 - Mozilla 开发者网络)。

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

localStorage 和 sessionStorage 非常适合在页面之间的客户端脚本中保留所需的非敏感数据(例如:首选项、游戏分数)。存储在 localStorage 和 sessionStorage 中的数据可以从客户端/浏览器中轻松读取或更改,因此不应依赖于在应用程序中存储敏感或与安全相关的数据。

Cookies

饼干

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 也是如此,它们可以被用户轻易篡改,并且数据也可以以纯文本形式从它们中读取 - 因此,如果您想存储敏感数据,那么会话实际上是您唯一的选择。如果您没有使用 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 becomethat user as far as the web application is concerned, and have the same access to data and functionality the user has.

从积极的方面来说,cookie 可以通过设置一个仅限 HTTP 的标志来防止跨站点脚本(XSS)/脚本注入等安全风险,这意味着现代(支持)浏览器将阻止从 JavaScript 访问 cookie 和值(这也将阻止您自己的合法 JavaScript 访问它们)。这对于身份验证 cookie 尤其重要,它用于存储包含登录用户详细信息的令牌 - 如果您拥有该 cookie 的副本,那么出于所有意图和目的,您就成为该用户,就 Web 应用程序而言相关,并具有与用户相同的数据和功能访问权限。

As cookies are used for authentication purposes and persistence of user data, allcookies valid for a page are sent from the browser to the server for everyrequest 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.

由于 cookie 用于身份验证目的和用户数据的持久性,因此对于对同一域的每个请求,对页面有效的所有cookie 都会从浏览器发送到服务器- 这包括原始页面请求、任何后续 Ajax 请求、所有图像、样式表、脚本和字体。因此,不应使用 cookie 来存储大量信息。浏览器还可能对可以存储在 cookie 中的信息大小施加限制。通常 cookie 用于存储用于身份验证、会话和广告跟踪的标识令牌。令牌本身通常不是人类可读的信息,而是链接到您的应用程序或数据库的加密标识符。

localStorage vs. sessionStorage vs. Cookies

localStorage 与 sessionStorage 与 Cookies

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.

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

Client-side vs. Server-side

客户端与服务器端

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

由于 HTTP 是一种无状态协议 - Web 应用程序无法在返回网站时从以前的访问中识别用户 - 会话数据通常依赖 cookie 令牌来识别重复访问的用户(尽管很少使用 URL 参数目的相同)。数据通常会有一个滑动的到期时间(每次用户访问时更新),并且根据您的服务器/框架数据将存储在进程中(意味着如果 Web 服务器崩溃或重新启动,数据将丢失)或外部存储状态服务器或数据库。这在使用网络农场(一个给定网站的多个服务器)时也是必要的。

As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.

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

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.

服务器端数据的明显缺点是可扩展性 - 在会话期间每个用户都需要服务器资源,并且客户端需要的任何数据都必须随每个请求一起发送。由于服务器无法知道用户是否导航到另一个站点或关闭了浏览器,因此会话数据必须在给定时间后过期,以避免所有服务器资源被放弃的会话占用。因此,在使用会话数据时,您应该注意数据可能已过期和丢失,尤其是在表单较长的页面上。如果用户删除他们的 cookie 或切换浏览器/设备,它也会丢失。

Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.

一些 Web 框架/开发人员使用隐藏的 HTML 输入将数据从表单的一个页面保存到另一个页面,以避免会话过期。

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.

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

For further reading on client storage technologies see Dive Into Html 5.

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

回答by softvar

  1. LocalStorage

    Pros:

    1. Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. If you look at the Mozilla source code we can see that 5120KB(5MBwhich equals 2.5 Million charson Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.
    2. 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.
    3. The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

    Cons:

    1. It works on same-origin policy. So, data stored will only be available on the same origin.
  2. Cookies

    Pros:

    1. Compared to others, there's nothing AFAIK.

    Cons:

    1. The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
    2. The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

      Typically, the following are allowed:

      • 300cookies in total
      • 4096 bytesper cookie
      • 20 cookiesper domain
      • 81920 bytesper domain(Given 20 cookies of max size 4096 = 81920 bytes.)
  3. sessionStorage

    Pros:

    1. It is similar to localStorage.
    2. The data is not persistent i.e. data is only available per window (or tab in browsers like Chrome and Firefox). Data is only available during the page session. 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.

    Cons:

    1. The data is available only inside the window/tab in which it was set.
    2. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.
  1. 本地存储

    优点

    1. Web 存储可以简单地视为对 cookie 的改进,提供了更大的存储容量。如果您查看 Mozilla 源代码,我们可以看到5120KB5MB,在 Chrome 上相当于250 万个字符)是整个域的默认存储大小。与典型的 4KB cookie 相比,这为您提供了更多的工作空间。
    2. 不会为每个 HTTP 请求(HTML、图像、JavaScript、CSS 等)将数据发送回服务器 - 减少客户端和服务器之间的流量。
    3. 存储在 localStorage 中的数据会一直存在,直到被明确删除。所做的更改将被保存并可供所有当前和将来访问该站点时使用。

    缺点

    1. 它适用于同源策略。因此,存储的数据只能在同一来源上使用。
  2. 饼干

    优点:

    1. 与其他人相比,没有什么是AFAIK。

    缺点:

    1. 4K 限制是针对整个 cookie,包括名称、值、到期日期等。为了支持大多数浏览器,将名称保持在 4000 字节以下,并且整个 cookie 大小在 4093 字节以下。
    2. 对于每个 HTTP 请求(HTML、图像、JavaScript、CSS 等),数据都会发送回服务器 - 增加了客户端和服务器之间的流量。

      通常,允许以下内容:

      • 总共300 个饼干
      • 每个 cookie 4096 字节
      • 每个域20 个 cookie
      • 每个域81920 字节(给定 20 个最大大小为 4096 = 81920 字节的 cookie。)
  3. 会话存储

    优点:

    1. 它类似于localStorage.
    2. 数据不是持久的,即数据仅适用于每个窗口(或 Chrome 和 Firefox 等浏览器中的选项卡)。数据仅在页面会话期间可用。所做的更改将被保存并可用于当前页面,以及将来在同一窗口中访问该站点。窗口关闭后,存储将被删除。

    缺点:

    1. 数据仅在设置它的窗口/选项卡内可用。
    2. 就像localStorage,它适用于同源策略。因此,存储的数据只能在同一来源上使用。

Checkout across-tabs- how to facilitate easy communication between cross-origin browser tabs.

Checkout跨标签- 如何促进跨源浏览器标签之间的轻松通信。

回答by Alireza

OK, LocalStorageas it's called it's local storage for your browsers, it can save up to 10MB, SessionStoragedoes the same, but as it's name saying, it's session based and will be deleted after closing your browser, also can save less than LocalStorage, like up to 5MB, but Cookiesare very tiny data storing in your browser, that can save up 4KBand can be accessed through server or browser both...

好的,LocalStorage顾名思义,它是浏览器的本地存储,最多可以节省10MBSessionStorage也一样,但顾名思义,它是基于会话的,关闭浏览器后将被删除,也可以节省比 LocalStorage 少,像高达5MB,但Cookies是存储在浏览器中的非常小的数据,最多可以节省4KB并且可以通过服务器或浏览器访问...

I also created the image below to show the differences at a glance:

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

LocalStorage, SessionStorage and Cookies

LocalStorage、SessionStorage 和 Cookie

回答by Prashant_M

These are properties of 'window' object in JavaScript, just like document is one of a property of window object which holds DOM objects.

这些是 JavaScript 中 'window' 对象的属性,就像 document 是保存 DOM 对象的 window 对象的属性之一。

Session Storage property maintains a separate storage area for each given origin that's available for the duration of the page session i.e as long as the browser is open, including page reloads and restores.

会话存储属性为每个给定的源维护一个单独的存储区域,在页面会话期间可用,即只要浏览器打开,包括页面重新加载和恢复。

Local Storage does the same thing, but persists even when the browser is closed and reopened.

本地存储做同样的事情,但即使在浏览器关闭并重新打开时仍然存在。

You can set and retrieve stored data as follows:

您可以按如下方式设置和检索存储的数据:

sessionStorage.setItem('key', 'value');

var data = sessionStorage.getItem('key');

Similarly for localStorage.

localStorage 也是如此。

回答by Srikrushna

Local storage:It keeps store the user information data without expiration date this data will not be deleted when user closed the browser windows it will be available for day, week, month and year.

本地存储:保存用户信息数据,无过期日期,用户关闭浏览器窗口时不会删除该数据,日、周、月、年均可使用。

In Local storage can store 5-10mb offline data.

在本地存储可以存储5-10mb的离线数据。

//Set the value in a local storage object
localStorage.setItem('name', myName);

//Get the value from storage object
localStorage.getItem('name');

//Delete the value from local storage object
localStorage.removeItem(name);//Delete specifice obeject from local storege
localStorage.clear();//Delete all from local storege

Session Storage:It is same like local storage date except it will delete all windows when browser windows closed by a web user.

会话存储:它与本地存储日期相同,但它会在网络用户关闭浏览器窗口时删除所有窗口。

In Session storage can store upto 5 mb data

在会话存储中最多可存储 5 mb 数据

//set the value to a object in session storege
sessionStorage.myNameInSession = "Krishna";

Session: A session is a global variable stored on the server. Each session is assigned a unique id which is used to retrieve stored values.

会话:会话是存储在服务器上的全局变量。每个会话都分配了一个唯一的 ID,用于检索存储的值。

Cookies: Cookies are data, stored in small text files as name-value pairs, on your computer. Once a cookie has been set, all page requests that follow return the cookie name and value.

Cookies:Cookies 是数据,以名称-值对的形式存储在您的计算机上的小型文本文件中。一旦设置了 cookie,随后的所有页面请求都会返回 cookie 名称和值。

回答by Developer

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.

  • Web 存储可以简单地视为对 cookie 的改进,提供了更大的存储容量。可用大小为 5MB,与典型的 4KB cookie 相比,可使用的空间要大得多。

  • 不会为每个 HTTP 请求(HTML、图像、JavaScript、CSS 等)将数据发送回服务器 - 减少客户端和服务器之间的流量。

  • 存储在 localStorage 中的数据会一直存在,直到被明确删除。所做的更改将被保存并可供所有当前和将来访问该站点时使用。

  • 它适用于同源策略。因此,存储的数据只能在同一来源上使用。

Cookies:

饼干:

  • We can set the expiration time for each cookie

  • The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.

  • The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

  • 我们可以为每个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。
  • 更改仅适用于每个窗口(或 Chrome 和 Firefox 等浏览器中的选项卡)。所做的更改将被保存并可用于当前页面,以及将来在同一窗口中访问该站点。窗口关闭后,存储将被删除。数据仅在设置它的窗口/选项卡内可用。

  • 数据不是持久的,即一旦窗口/选项卡关闭,它就会丢失。与 localStorage 一样,它适用于同源策略。因此,存储的数据只能在同一来源上使用。

回答by Yash

The Web Storage API provides mechanisms by which browsers can securely store key/value pairs, in a much more intuitive fashion than using cookies. The Web Storage APIextends the Windowobject with two new properties — Window.sessionStorageand Window.localStorage. — invoking one of these will create an instance of the Storage object, through which data items can be set, retrieved, and removed. A different Storage object is used for the sessionStorageand localStoragefor each origin (domain).

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

Storage objects are simple key-valuestores, similar to objects, but they stay intact through page loads.

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

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

The keys and the values are always strings. To store any type convert it to Stringand then store it. It's always recommended to use Storage interfacemethods.

键和值始终是字符串。存储任何类型convert it to String,然后存储它。始终建议使用Storage interface方法。

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

The two mechanisms within Web Storage are as follows:

Web Storage 中的两种机制如下:

  • sessionStoragemaintains a separate storage area for each given originSame-origin policythat's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
  • localStoragedoes the same thing, but persists even when the browser is closed and reopened.
  • sessionStorage为每个给定的原始同源策略维护一个单独的存储区域,该策略在页面会话期间可用(只要浏览器打开,包括页面重新加载和恢复)。
  • localStorage做同样的事情,但即使在浏览器关闭并重新打开时仍然存在。

Storage? Local storagewrites the data to the disk, while session storage writes the data to the memory only. Any data written to the session storage is purged when your app exits.

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

The maximum storage available is different per browser, but most browsers have implemented at least the w3c recommended maximum storage limit of 5MB.

每个浏览器最大可用存储空间不同,但大多数浏览器至少实现了 w3c 建议的最大存储空间限制5MB

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

Always catch LocalStorage security and quota exceeded errors

始终捕获 LocalStorage 安全性和超出配额的错误

StorageEvent? The storage event is fired on a document's Window object when a storage area changes. When a user agent is to send a storage notification for a Document, the user agent must queue a task to fire an event named storage at the Document object's Window object, using StorageEvent.

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

Note: For a real world example, see Web Storage Demo. check out the source code

注意:有关真实示例,请参阅Web 存储演示查看源代码

Listen to the storage event on dom/Window to catch changes in the storage. fiddle.

侦听 dom/Window 上的存储事件以捕获存储中的更改。小提琴



Cookies(web cookie, browser cookie) Cookies are data, stored in small text files as name-value pairs, on your computer.

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

JavaScript access using Document.cookie

使用Document.cookie访问 JavaScript

New cookies can also be created via JavaScript using the Document.cookie property, and if the HttpOnly flag is not set, existing cookies can be accessed from JavaScript as well.

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

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

Secure and HttpOnly cookies HTTP State Management Mechanism

安全和 HttpOnly cookie HTTP 状态管理机制

Cookies are often used in web application to identify a user and their authenticated session

Cookie 通常用于 Web 应用程序中以识别用户及其经过身份验证的会话

When receiving an HTTP request, a server can send a Set-Cookieheader with the response. The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header.

当接收到 HTTP 请求时,服务器可以发送带有响应的Set-Cookie标头。cookie 通常由浏览器存储,然后 cookie 与对同一服务器的请求一起发送到 cookie HTTP 标头内。

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

Session cookieswill get removed when the client is shut down. They don't specify the Expires or Max-Age directives.

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

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

Permanent cookiesexpire at a specific date (Expires) or after a specific length of time (Max-Age).

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

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

The Cookie HTTP request header contains stored HTTP cookies previously sent by the server with the Set-Cookie header. HTTP-only cookies aren't accessible via JavaScript through the Document.cookie property, the XMLHttpRequest and Request APIs to mitigate attacks against cross-site scripting (XSS).

Cookie HTTP 请求标头包含存储的 HTTP cookie,之前由服务器使用 Set-Cookie 标头发送。无法通过 JavaScript 通过 Document.cookie 属性、XMLHttpRequest 和请求 API 访问仅 HTTP cookie,以减轻对跨站点脚本 (XSS) 的攻击。

Cookies are mainly used for three purposes:

Cookies主要用于三个目的:

  • 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。如果域不同,则称其为第三方 cookie。虽然第一方 cookie 仅发送到设置它们的服务器,但网页可能包含存储在其他域的服务器上的图像或其他组件(如广告横幅)。通过这些第三方组件发送的 Cookie 称为第三方 Cookie,主要用于网络广告和跟踪。

Cookies were invented to solve the problem "how to remember information about the user":

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

  • When a user visits a web page, his name can be stored in a cookie.
  • Next time the user visits the page, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.
  • 当用户访问网页时,他的姓名可以存储在 cookie 中。
  • 下次用户访问该页面时,属于该页面的 cookie 将添加到请求中。通过这种方式,服务器获得必要的数据来“记住”有关用户的信息。

GitHubGist Example

GitHubGist示例



As summary,

作为总结,

  • 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 持续存在于不同的选项卡或窗口中,即使我们关闭浏览器,也会相应地与域安全策略和用户对配额限制的选择有关。
  • 如果我们关闭选项卡(顶级浏览上下文), sessionStorage 对象不会持续存在,因为如果我们通过另一个选项卡或窗口冲浪,它就不存在。
  • Web 存储(会话、本地)允许我们保存大量键/值对和大量文本,这是通过 cookie 无法做到的。
  • 用于敏感操作的 Cookie 应该只有很短的生命周期。
  • Cookie 主要用于网络广告和跟踪。例如,参见Google 使用的 cookie 类型
  • 每个请求都会发送 Cookie,因此它们会降低性能(尤其是对于移动数据连接)。用于客户端存储的现代 API 是 Web 存储 API(localStorage 和 sessionStorage)和 IndexedDB。