localStorage、sessionStorage、session和cookie的技术优缺点是什么,什么时候使用其中一个而不是另一个?
当前回答
这里是一个快速的回顾和简单而快速的理解
来自freecodecamp的Beau Carnes教练
其他回答
确切的用例-
如果您希望页面始终保存一些非机密的数据,那么可以使用localStorage。 如果服务器需要知道一些信息,比如身份验证密钥,您应该使用cookie来存储它们。 sessionStorage可用于存储界面的状态,即,无论何时访问一个页面,定制它,访问另一个页面并返回到同一页面,您都希望显示用户如何定制该页面。这是sessionStorage的一个很好的用例。
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:
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,可以通过服务器或浏览器访问…
我还创建了下面的图像来显示差异:
本地存储:保存没有过期日期的用户信息数据,当用户关闭浏览器窗口时,这些数据不会被删除,它将在天,周,月和年可用。
本地存储可以存储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
会话存储:它与本地存储日期相同,只是当web用户关闭浏览器窗口时,它会删除所有窗口。
在会话存储可以存储高达5 mb的数据
//set the value to a object in session storege
sessionStorage.myNameInSession = "Krishna";
会话:会话是存储在服务器上的全局变量。每个会话都分配了一个惟一的id,用于检索存储的值。
cookie: cookie是数据,以名称-值对的形式存储在计算机上的小文本文件中。一旦设置了cookie,随后的所有页面请求都会返回cookie名称和值。