Browser storage
This is the 14th day of my participation in Gwen Challenge
When it comes to browser storage, we hear about cookies, localStorage and sessionStorage the most. What’s the difference between cookie and session and sessionId? Let’s learn about it together.
First, the browser storage method
features | cookie | localStorage | sessionStorage | indexedDB |
---|---|---|---|---|
Data life cycle | Generally, it is generated by the server. You can set the expiration time | Unless it’s cleaned up, it’s always there | Clean up when the page is closed | Unless it’s cleaned up, it’s always there |
Data store size | 4K | 5M | 5M | infinite |
Communicates with the server | It is carried in the header each time and has an impact on request performance | Don’t participate in | Don’t participate in | Don’t participate in |
Add: Cookie is not used to store, but to communicate with the server, need to access please own encapsulation API.
LocalStorage has its own getItem and setItem methods, it is very convenient to use.
LocalStorage Note:
-
LocalStorage can only store strings. Access JSON data with json.stringify () and json.parse ().
-
If setItem is disabled, try… Catch Catches an exception.
Cookie, localStorage and sessionStorage
What are cookie, localStorage, and sessionStorage?
(1) the cookie
-
A cookie is a very specific thing. It refers to a kind of data that can be stored permanently in the browser. It’s just a data storage function implemented by the browser.
-
The cookie is generated by the server and sent to the browser, which saves the cookie in the form of KV in a text file in a directory. The cookie will be sent to the server when the same website is requested next time.
-
The cookie expiration time is set by the client. If the expiration time is not set, it indicates that the lifetime of the cookie is during the browser session. When the browser window is closed, the cookie disappears. Cookies with a lifetime of a browser session are called session cookies. If an expiration time is set, the cookie remains valid until the set expiration time, even if the window or browser is closed.
-
Session cookies are generally stored in memory rather than hard disk, although this behavior is not regulated by the specification. If the expiration time is set, the browser saves cookies to the hard disk, closes the browser, opens the browser, and these cookies remain valid until the expiration time is exceeded. Different browsers have different ways of dealing with cookies that are stored in memory.
-
You can use document.cookie = “” to set the value of the cookie. Cookie values exist as key-value pairs. If the keys are set the same, the original values will be overwritten. When the keys are different, the pair is superimposed. Here attached is an article about how to set cookies that I have read and think is easier to understand. You can view it according to your own needs
(2) the localStorage
- It is always valid and is always saved when a window or browser is closed and therefore used as persistent data;
- Same-origin Windows are shared and not invalidated, and remain in effect whether the window or browser is closed or not.
(3) the sessionStorage
-
A form of browser storage.
-
It is valid only before the current browser window closes and cannot be persistent.
-
In the same browser, if you jump to a new page from the current page, you can share it. However, if you open a new page directly, you cannot share it.
2. Similarities and differences between Cookie, localStorage and sessionStorage
(1) The similarities of the three are:
- All are saved on the browser side and are homologous.
(2) The differences among the three are as follows:
-
Communication with the server is different:
Cookie data is always carried in same-origin HTTP requests (even if it is not needed), i.e. cookies are passed back and forth between the browser and the server, whereas sessionStorage and localStorage do not automatically send data to the server, only locally stored;
Cookies are sent out with HTTP requests, while loacalStorage and sessionStorage are not sent out with HTTP requests.
Cookie data also has the concept of path, which can restrict cookies to a specific path.
-
Storage size limits also differ:
Cookie data cannot exceed 4K, and because each HTTP request carries cookies, cookies are only suitable for storing small data, such as session id;
SessionStorage and localStorage, while also limited in size, are much larger than cookies, reaching 5M or more.
-
Different data validity periods:
SessionStorage: only valid until the current browser window closes;
LocalStorage: always valid, saved even when the window or browser is closed and therefore used as persistent data;
Cookie: Only valid before the set cookie expiration time, even if the window is closed or the browser is closed.
-
Different scopes:
SessionStorage is not shared across different browser Windows, even on the same page;
Localstorage and cookies are shared in all same-origin Windows;
3. Use of cookies
(1) Save the user login status
For example, storing the user ID in a cookie so that the user does not need to log in again the next time they visit the page is a feature that is now available in many forums and communities.
Cookies can also set the expiration time, when the time limit is exceeded, the cookie will automatically disappear. As a result, the system can often prompt users for how long they want to stay logged in: common options are one month, three months, a year, and so on.
(2) Tracking user behavior
A weather website, for example, can display local weather conditions based on the region selected by the user. If it is tedious to choose the location every time, it will appear very humanized after using cookies. The system can remember the region visited last time, and when opening the page next time, it will automatically display the weather situation of the region where the user was last time.
Because everything is done in the background, such pages are very easy to customize as if they were customized for a particular user. If the site provides the ability to change the skin or layout, you can use cookies to record the user’s options, such as background color, resolution, etc. When the user visits the interface next time, the interface style of the last visit can still be saved.
Session and Token
(1) the Session
Here’s an example:
session
Literally, yesThe session. It’s kind of like when you’re talking to someone, how do you know that you’re talking to A Joe and not a Joe? There must be something about the other person (looks, height, etc.) that says he is Zhang SAN.session
Similarly, the server needs to know who is currently sending the request to it.- To make this distinction, the server assigns a different”identity“, this identity means what we usually say
sessionId
. And then every time the client sends a request to the server, it carries this”identity“, and the server knows who the request came from. - As for how the client saves this.”identityFor browser clients, the default is used in most cases
cookie
Of course, can also be usedlocalStorage
和sessionStorage
Store thisidentity, you can use it according to your own needs. - It’s important to note that,
session
For a session, even if the same page is opened twice, it is considered the same session. - Server usage
session
Put the user’s informationtemporarySaved on the server after the user leaves the sitesession
Will be destroyed. - This kind of user information storage method is relative
cookie
It’s safer to talk, butsession
There is adefects: If the Web server is load balanced, then the next operation request arrives at another serversession
Will be lost.
To sum up, session:
- When the program needs to create one for a client request
session
The server first checks to see if the client’s request already contains onesession
Identification (known assessionId
), if it has been previously created for this clientsession
, the server does thissessionId
I’m going to put the corresponding thetasession
Retrieves out to use (retrieves not, will create a new); Otherwise, if the client request does not containsessionId
, creates one for the clientsession
And generate one with thissession
The associatedsessionId
,sessionId
The value of should be a string that is neither repetitive nor easy to find patterns to mimicsessionId
Will be returned to the client for saving in this response. Save thissessionId
Can be adoptedcookie
Or it could belocaStorage
和sessionStorage
So that the browser can automatically send the identity to the server according to the rules during the interaction.
(2) Token
-
Token-based authentication is ubiquitous in the Web world. In most Internet companies that use Web APIS, tokens are the best way to handle authentication under multiple users.
-
The following features allow you to use token-based authentication in your application:
- Stateless and extensible;
- Support for mobile devices;
- Cross-program call;
- Security.
-
Most of the apis and Web applications you’ll see use tokens. Facebook, Twitter, Google, GitHub, etc.
Fourth, concluding remarks
Cookie, loacalStorage, and sessionStorage are common interview questions. In the process of learning, to understand the relationship between cookie, localStorage and sessionStorage, as well as the relationship between session, sessionId and cookie, only by understanding the relationship between them. I’m not stuck in a relationship mess.
So much for browser storage! If you have any questions or the article is wrong, please leave a message in the comment area or send a private message to me
Pay attention to the public number Monday laboratory, the first time to pay attention to learning dry goods, more interesting columns for you to unlock ~
If this article is useful to you, be sure to like it and follow it
Dragon Boat Festival ankang, we see you next time! 🥂 🥂 🥂