Detailed explanation of cookie, localStorage and sessionStorage

 

Table of contents

1. Cookies

2. Web storage

1、localStorage

2. The use of sessionStorage

 3. Complex data type storage

Benefits of Web Storage: 

3. The difference between sessionStorage, localStorage and cookie 


1. Cookies

A cookie is a technology that can be stored locally in the browser and used by the client to communicate with the server. In short, a cookie is a text file sent from the server to the client, but it can only store 4kb of data; the purpose is to identify the user's identity, record and track product information (such as quantity) in the shopping cart, and record the number of user visits, etc.

The content of the cookie mainly includes: name name, value value, expiration time expires, path path and domain domain. Path and domain together form the scope of the cookie. Generally, the cookie is stored in memory, and if an expiration time is set, it will be stored in the hard disk, and the browser page will not be invalidated until the expiration time is set. If the expiration time of the cookie is not set, the validity period is the session period of the browser window, and it will be invalid when the browser window is closed.

principle:

When the client requests the server, if the server needs to record the user status, it uses response to issue a cookie to the client browser. The client browser will save the cookie. When the browser requests the server again, the browser submits the requested URL together with the cookie to the server. The server obtains user status by checking this cookie.

Set cookie: document.cookie = "key=value;";

setCookie(name,value,expiredays){//设置时间为天为过期单位
      var exdate=new Date();
      exdate.setDate(exdate.getDate()+expiredays);
      document.cookie=name + '=' + escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
    },

get cookie

getCookie(name){
      var start = document.cookie.indexOf(name+'=')
      var end = document.cookie.indexOf(';',start)
      if(end=-1){
        end = document.cookie.length
      }
      return unescape(document.cookie.substring(start,end))
    }

2. Web storage

The concept of web Storeage is very similar to cookie, the difference is that web Storage is more than enough to store various data, the size of cookie is limited, and every time a new page is requested, it will be sent to the past, which wastes bandwidth virtually. In addition, the cookie also needs to specify the scope, and cannot be called across.

HTML5 adds two storage methods: localStorage and sessionStorage

1、localStorage

The life cycle of localStorage is permanent. Unless manually cleared, it will always exist. Its storage size is 5MB. It is only stored on the client browser and does not participate in server communication.

How to use localStorage

      //设置localStorage保存到本地,第一个为变量名,第二个是值
      localStorage.setItem('Author', 'Jane')
      // 获取数据
      localStorage.getItem('Author')
      // 删除保存的数据
      localStorage.removeItem('Author')
      // 清除所有保存的数据
      localStorage.clear()

  Usually stored as key-value pairs, usually as strings

2. The use of sessionStorage

 As the name implies, sessionStorage is valid under the current session, and a "browser window concept" is introduced. SessionStorage is the data that always exists in the same window of the same source. Another page, the data is still there. Open an "independent" window at the same time, even if it is the same page, the object of sessionStorage is different. sessionStorage will be destroyed after closing the window.

 How to use sessionStorage

      // 设置sessionStorage保存到本地,第一个为变量名,第二个是值
      sessionStorage.setItem('sessionName', 'John')
      // 获取数据
      sessionStorage.getItem('sessionName')
      // 删除保存的数据
      sessionStorage.removeItem('sessionName')
      // 清除所有保存的数据
      sessionStorage.clear()

For example, set the sessionName of sessionStorage to John

 Click the button to trigger the change method, change the sessionName to dell,

 change () {
      sessionStorage.setItem('sessionName', 'dell')
      this.sessionName = sessionStorage.getItem('sessionName')
    }

 

 Open an independent window again, and you will find that the value of sessionStorage is still the initial value, indicating that the objects of sessionStorege in different windows are different, and the value of localStorage is changed synchronously.

 3. Complex data type storage

As mentioned above, webStorage is stored in string format, so objects and array types cannot be stored directly, and the format needs to be converted before storage.

 Use JSON.stringify() to convert an object to a string

When parsing, use JSON.parse() to convert back to use.

Benefits of Web Storage: 


1. Reduce network traffic: Once the data is stored locally, it is possible to avoid requesting data from the server, thus reducing unnecessary data requests and data


2. Fast display of data: good performance, reading data locally is much faster than obtaining data from the server through the network, local data can be obtained in time, coupled with Internet access 

The page itself can also have a cache, so if the entire page and data are local, it can be displayed immediately 
3. Temporary storage: In many cases, the data only needs to be used while the user browses a set of pages, and the data can be discarded after closing the window. It is very convenient to use sessionStorage

3. The difference between sessionStorage, localStorage and cookie 

What they have in common: They are all saved on the browser side and have the same origin. 
Differences: 
1. Cookie data is always carried in the http request of the same origin (even if it is not needed), that is, cookies are passed back and forth between the browser and the server, while sessionStorage and localStorage will not automatically send the data to the server, but only save it locally. Cookie data also has the concept of path (path), which can limit the cookie to only belong to a certain path 
. Small data, such as session IDs. Although sessionStorage and localStorage also have storage size limitations, they are much larger than cookies, and can reach 5M or more. 
3. Data validity periods are different. sessionStorage: only valid until the current browser window is closed; localStorage: always valid, window or browser It is always saved when closed, so it is used as persistent data; cookie: only valid until the set cookie expiration time, even if the window is closed or the browser is closed 
4. The scope is different, sessionStorage is not shared in different browser windows, even if it is the same Pages; localstorage is shared in all windows of the same origin; cookies are also shared in all windows of the same origin 
5. web Storage supports event notification mechanism, which can send notifications of data updates to 
listeners The api interface is more convenient to use

Guess you like

Origin blog.csdn.net/m0_37756431/article/details/123536611