Cookie与网络存储

Cookies vs. Web storage

本文关键字:存储 网络 Cookie      更新时间:2023-09-26

我正在创建一个项目,我想在其中保存用户达到的最后一个级别,以便他们下次可以继续他们停止的地方。我想知道我是应该使用cookie还是网络存储,以及使用每种cookie的原因。例如,一个会影响性能吗,是一个通常启用/禁用的,是现代浏览器不支持的,等等。

我还想知道,除了这两个选项之外,是否还有其他选项可以替代,以及这些选项的优点和缺点是什么。

谢谢!

**Cookies**
Pros
1. Legacy support (it's been around forever)
2. Persistent data
3. Expiration dates
Cons
1. Each domain stores all its cookies in a single string, which can make parsing data difficult
2. Data is unencrypted.
3. small in size, cookies are sent with every HTTP request
4. Limited size (4KB)
5. SQL injection can be performed from a cookie
**Local storage / Web storage**
Pros
1. Support by most modern browsers
2. Persistent data that is...
3. stored directly in the browser
4. Same-origin rules apply to local storage data
5. Is not sent with every HTTP request
6. ~5MB storage per domain (that's 5120KB)
Cons
Not supported by anything before:
1. IE 8
2. Firefox 3.5
3. Safari 4
4. Chrome 4
5. Opera 10.5
6. iOS 2.0
7. Android 2.0
8. If the server needs stored client information you purposefully have to send it. [3]
Based on my comparison I think that local storage is the logical successor of cookies for storing client-side data. While cookies were originally created as a work-around, local storage has been designed with a purpose.
Local storage is easier to work with because you don't have to parse a string to get data. Instead you can make a call for the variable name and it's value is returned. The same applies with creating and deleting data as well.
For saving client-side data I believe local storage wins. As someone on the stackoverflow boards pointed out however, if your server needs information from a client cookies will be a better solution. But if you just want to save user-prefs, num vists, or other stuff like that choose local storage.

它们的目的完全不同。Cookie可从服务器获得,而Web存储仅可用于客户端。每个请求,cookie都将与HTTP头一起发送到服务器。当服务器不需要数据时,就不需要这样做了。在这种情况下,Web存储可能是最好的选择。

这完全取决于您希望谁能够访问数据。

Web存储提供了一种永久存储数据的方式(直到用户清除浏览器缓存),而cookie则设置为在一定时间后过期。

Web存储也更适合存储大块数据,比如数据的完整JSON表示(最高5MB)。从IE8及更高版本开始支持Web存储,所以这应该没有问题。