With the improvement of browser storage technology, the function of cookie to store data has become difficult to meet the development requirements, and is gradually replaced by WebStorage and IndexedDB. The differences, advantages and disadvantages of these storage methods are described below.
A, Cookie,
The source of the Cookie
The job of a Cookie is not to store it locally, but to “maintain state.”
Because HTTP is stateless, the HTTP protocol itself does not store the state of communication between a request and a response. In layman’s terms, the server does not know what the user did last time, which seriously impedes the implementation of interactive Web applications.
We can think of a Cookie as a little text file stored in a browser, attached to an HTTP request, that flies back and forth between the browser and the server. It can carry user information, and when the server checks the Cookie, it can get the status of the client.
What are cookies and application scenarios
HTTP cookies (also called Web cookies or browser cookies)
Is the server sends to the user’s browser and a piece of data stored on the local (usually encrypted), it will be the next to the same server to the browser sends the request again be taken and sent to the server, usually, it is used to inform the server whether two requests from the same browser, such as keep the user logged in. Cookies make it possible for stateless HTTP protocols to record stable state information.
Cookies are in the form of key-value pairs
Cookies are mainly used for the following three aspects:
- Session state management (such as user login status, shopping cart, game score, or other information that needs to be logged)
- Personalization (such as user-defined Settings, themes, etc.)
- Browser behavior tracking (e.g. tracking and analyzing user behavior, etc.)
The principle and generation method of Cookie
The first time you visit a website, the browser sends a request and the server responds to the request, adding a set-cookie option to the response header and placing the Cookie in the response request.
When the browser sends a request for the second time, it sends the Cookie information to the server through the Cookie request header, and the server identifies the user.
In addition, Cookie expiration time, domain, path, expiration date, and applicable site can be specified as required.
However, we generally do not store user information (such as user name, shopping cart goods, etc.) in cookies. On the one hand, cookie storage space is limited, and the data saved by a single cookie cannot exceed 5K. On the other hand, cookie security is low. We generally use session to record user information and cookie to record session ids.
Here we need to introduce the concept of session.
What is a Session
Session represents a Session between the server and the client.
The server creates a specific Session to identify and track users. It is stored on the server and has a Session ID that uniquely identifies it.
The Session object stores properties and configuration information required for a specific user Session. This way, variables stored in the Session object will not be lost when the user jumps between Web pages of the application, but will persist throughout the user Session.
The Session ends when the client closes the Session or the Session times out.
How does the server identify a particular client?
This is where Cookie comes in. Each TIME an HTTP request is made, the client sends a Cookie to the server. In fact, most applications use cookies to implement Session tracking.
When a Session is first created, the server will tell the client in the HTTP protocol that it needs to record a SessionID in the Cookie. After each request, this SessionID will be sent to the server, so I know who you are.
A session relies on the session ID, which is stored in a cookie
What if the browser disables cookies?
-
Session tracking is done using THE URL rewriting technique (passing session_id in the URL), where each HTTP interaction is followed by a parameter such as sid= XXXXX, by which the server identifies the user.
-
Token mechanism.
Token means “Token” and is a string generated by a server as an identifier for a client to make a request. The Token mechanism is similar to the Cookie and Session mechanism. When a user logs in for the first time, the server generates a Token based on the submitted user information and returns the Token to the client. In the future, the client only needs to bring the Token to request data without logging in again.
How cookies are generated
- Set-cookie in HTTP Response header
- Js can read and write cookies via document.cookie and display them as key-value pairs.
The defect of the Cookie
-
Cookie Not big Enough The size of a single Cookie key-value pair is limited to about 4KB, which is not enough for complex storage requirements. When a Cookie exceeds 4KB, it will be pruned. Many browsers also limit the number of cookies a site can have.
-
Too many cookies can be a huge performance waste because cookies follow the domain name, all requests under the same domain name carry cookies. Cookies are small, but requests can be numerous, and the overhead of unnecessary cookies is unimaginable as requests pile up.
-
Because cookies in HTTP requests are passed in plain text, security is problematic unless HTTPS is used
In order to make up for the limitations of cookies, let “professional people do professional things”, Web Storage appeared. HTML5 new localStorage solutions – Web Storage, it is divided into two categories: sessionStorage and localStorage. With WebStorage, cookies can only do what they are supposed to do — act as a channel through which the client interacts with the server, keeping the client state.
Second, the LocalStorage
The characteristics of
- The saved data exists for a long time, and the next time you visit the site, the page can read the previously saved data directly.
- The size is about 5M
- It is used only on the client and does not communicate with the server
- Good interface encapsulation
Based on the above features, LocalStorage can be used as a browser local cache solution to improve the speed of rendering the first screen of a web page (when the first request is returned from the base, some unchanged data is directly stored locally).
Store/read data
Data stored in localStorage is in key-value pairs. That is, each item of data has a key name and corresponding value. All data is stored in text format.
In the data
localStorage.setItem("key"."value");
Copy the code
Read the data
localStorage.getItem("key");
Copy the code
Here’s an example:
<script>
if(window.localStorage){
localStorage.setItem("name"."world");
localStorage.setItem("gender"."famale");
}
</script>
<body>
<div id="name"></div>
<div id="gender"></div>
<script>
var name = localStorage.getItem("name");
var gender = localStorage.getItem("gender");
document.getElementById("name").innerHTML=name;
document.getElementById("gender").innerHTML=gender;
</script>
</body>
Copy the code
Usage scenarios
LocalStorage has no special limitations on storage. In theory, it can do all the data storage tasks that cookies cannot do and can be accessed with simple key-value pairs.
For example, given that one of the characteristics of LocalStorage is persistence, we sometimes prefer to use it to store content stable resources, such as image-rich e-commerce sites that use it to store Base64 image strings.
Third, sessionStorage
SessionStorage stores data for a session in the browser. When the session ends (usually when the window closes), the data is cleared.
The special feature of sessionStorage is that even if two pages under the same domain name are not opened in the same browser window, their sessionStorage content cannot be shared.
LocalStorage and cookies are shared in all same-origin Windows.
The characteristics of
- Session-level browser storage
- The size is about 5M
- It is used only on the client and does not communicate with the server
- Good interface encapsulation Based on the above features, sessionStorage can effectively maintain form information, such as refresh, form information is not lost.
Usage scenarios
SessionStorage is more suitable for storing life-cycle and session-level information that it synchronizes. This information only applies to the current session, and when you start a new session, it needs to be updated or released accordingly.
The difference between sessionStorage, localStorage and cookie
Common: Both are saved in the browser and comply with the same origin policy
Difference: In life cycle and scope
Scope: As long as localStorage is in the same protocol, the same host name, the same port, can read/modify to the same localStorage data. SessionStorage is more strict than localStorage, in addition to protocol, host name, port, but also in the same window (that is, the browser TAB page).
Life cycle: localStorage is persistent localStorage, stored in the data is never expired, the only way to make it disappear is to manually delete; SessionStorage is temporary local storage, it is session level storage, when the session ends (the page is closed), the storage content is also released.
Web Storage is a very simple thing to define and use. It can only be used to store small amounts of simple data. IndexedDB is the ultimate Boss when it comes to large, complex data that Web Storage can’t help
Four, with IndexedDB
IndexedDB is a low-level API for clients to store large amounts of structured data (including files and blobs) that uses indexes to enable high-performance searches of that data.
IndexedDB is a non-relational database that runs on a browser. Theoretically, IndexedDB has no storage ceiling and can store not only strings but binary data.
The characteristics of
- Key-value pair storage
- asynchronous
- Support transactions
- The same-origin restrictions
- Large storage space
- Support binary storage