localStorage、sessionStorage、session和cookie的技术优缺点是什么,什么时候使用其中一个而不是另一个?
当前回答
这是一个非常宽泛的问题,很多优点和缺点都要根据具体情况而定。
在所有情况下,这些存储机制将特定于单个计算机/设备上的单个浏览器。任何跨会话持续存储数据的需求都需要应用程序服务器端参与—很可能使用数据库,但也可能使用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教练
本地存储:保存没有过期日期的用户信息数据,当用户关闭浏览器窗口时,这些数据不会被删除,它将在天,周,月和年可用。
本地存储可以存储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名称和值。
LocalStorage Pros: 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 (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain. This gives you 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. Cons: It works on same-origin policy. So, data stored will only be available on the same origin. Cookies Pros: Compared to others, there's nothing AFAIK. Cons: 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. Typically, the following are allowed: 300 cookies in total 4096 bytes per cookie 20 cookies per domain 81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.) sessionStorage Pros: It is similar to localStorage. 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 tab/window. Once the tab/window is closed, the data is deleted. Cons: The data is available only inside the window/tab in which it was set. 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,可以通过服务器或浏览器访问…
我还创建了下面的图像来显示差异:
确切的用例-
如果您希望页面始终保存一些非机密的数据,那么可以使用localStorage。 如果服务器需要知道一些信息,比如身份验证密钥,您应该使用cookie来存储它们。 sessionStorage可用于存储界面的状态,即,无论何时访问一个页面,定制它,访问另一个页面并返回到同一页面,您都希望显示用户如何定制该页面。这是sessionStorage的一个很好的用例。