Cookie, localStorage, SessionStorage difference and application scenarios

Cookie, localStorage, SessionStorage difference and application scenarios

What is a cookie?

Cookie: The data stored on the user’s local terminal.
Cookie is literally translated into Chinese as a small cookie. As the name suggests, its memory is very small, and the size is limited to about 4KB.
Every http request will carry a very small cookie.

localStorage

It is a new technology of H5
. Data storage without time limit. The next day, next week, next year, it will still exist as long as you don’t delete it.

SessionStorage

For the data storage of a session, when the user closes the browser, the data will be deleted

The difference between the three

characteristic Cookie localStorage sessionStorage
Data life cycle Generally generated by the server, the expiration time can be customized, if generated by the browser, the default is to expire when the browser is closed As long as it is not deleted, it will always exist Only in the current session, it will be invalid when you close the webpage or close the browser
Stored data size Generally 4KB Up to 5MB Up to 5MB
Communication with the server It will be carried in the HTTP header every time. Generally, the data in the Cookie cannot be saved too much, otherwise it will affect the performance problem Only save in the client (browser), do not participate in the communication with the server Only save in the client (browser), do not participate in the communication with the server
Ease of use Programmers encapsulate themselves, the original Cookie interface is not friendly The native interface is acceptable, but you can also encapsulate it yourself, which is more usable for Object and Array The native interface is acceptable, but you can also encapsulate it yourself, which is more usable for Object and Array
Scope Shared with all same-origin windows Shared with all same-origin windows Do not share in different browser windows

Application scenarios

Cookie:

  • It is generally used to determine whether the user has logged in to the website, so that the next time you log in, you can automatically log in or remember the password. If we delete the content in the Cookie, you need to fill in all relevant information the next time you log in
  • Save information such as the time of last login
  • Save the last viewed page
  • Save the number of views

localStorage:

  • JS, CSS for caching the content of static files
  • Cache API interface data that is not frequently used
  • Store geographic location

SessionStorage:

Used for one-time login of sensitive accounts. When the page is closed at the time and the page is opened again, you need to log in again

Guess you like

Origin blog.csdn.net/rraxx/article/details/114024959