Cookies and local storage

table of Contents

1.cookie

1 The role and characteristics of cookies

1.1 Function

1.2 Complete format

1.3 Features

1.4 Chinese encoding

2. Set cookies

3. Set cookie time

4. Set multiple cookies

5. Set the common attributes of all cookies

2. Local storage

1.Storage

1.1 Session Storage

1.2 Local Storage

2. Features of storage

3. storage API

4. Case


1.cookie

It was proposed by the W3C organization and was first developed by the Netscape community. Since HTTP is a stateless protocol, the server cannot know the identity of the client from the network connection alone. How to do it? Just issue a pass to the clients, one for each person, no matter who visits you must bring your own pass. In this way, the server can confirm the identity of the customer from the pass. This is how cookies work.

Briefly talking about cookie session tracking technology

During the entire process from the beginning to the end of a session, the status of the client is tracked and recorded throughout the process, such as whether it is logged in, shopping cart information, whether it has been downloaded, whether it has been liked, video playback progress, etc.

1 The role and characteristics of cookies

Cookies are cached information stored in browsers.

1.1 Function

  1. registration record
  2. Data transfer for multiple pages
  3. Save user information

1.2 Complete format

name=value;[expires=date];[path=path]

 1.3 Features

  1. The stored value will not be very large (up to 4kb each time)
  2. Store up to 50 messages under each domain name (different browsers will be slightly different)
  3. Non-cross-domain
  4. You can set the expiration time yourself

1.4 Chinese encoding

Chinese and English characters are different. Chinese belongs to Unicode characters and occupies 4 characters in memory, while English belongs to ASCII characters and only occupies 2 bytes in memory. Unicode characters need to be encoded when using Unicode characters in cookies, otherwise they will be garbled.

Therefore, garbled characters may appear in cookies stored directly in Chinese.

encodeURIComponent compiles Chinese into corresponding characters

decodeURIComponent converts the corresponding character to Chinese

2. Set cookies

Set cookie

document.cookie = 'name=hello'

The default setting cookie expiration time is when the browser is closed.

3. Set cookie time

Use expires to set the cookie expiration time.

        let date = new Date().getTime();
        let outTimer = date + 24 * 60 * 60 * 1000  //设置cookie一天以后过期
        let outDate = new Date(outTimer);
        document.cookie = "name = hello;expires=" + outDate;
        console.log(document.cookie);

 Open the developer tools in the browser, you can see the cookie expiration time we set under application.

Because we set the cookie to expire after one day, so in Expires, the expiration time is 2020-3-30 13:56:59 ...

Note: When setting the expiration time, it cannot be less than the current time.

        let date = new Date(0);
        console.log(date);
        document.cookie = "name = hello;expires=" + date;
        console.log(document.cookie)

You can clearly see that the second printed content is empty.

4. Set multiple cookies

        let date = new Date().getTime();
        let outTimer = date + 24*60*60*1000;  //设置cookie一天以后过期
        let outDate = new Date(outTimer);
        document.cookie = "name = hello ; expires = " + outDate;
        document.cookie = 'password = 123456 ; expries = ' + outDate;
        console.log(document.cookie);

 Print two cookie information.

5. Set the common attributes of all cookies

Attributes description
Name Set the name of the cookie, which cannot be changed once it is determined
Value  The value of this cookie. If the value is a Unicode character, you need to encode the character.
Domain You can access the cookie's yuming (localhost)
Path Current cookie usage path
Expires Set cookie expiration time
Max-Age Set cookie lifetime in seconds
HttpOnly Tell the browser that the cookie cannot be accessed through the document.cookie property of javaScript
Secure

Whether the cookie is only transmitted using a secure protocol.

Security Protocol. The default is false. If you do not set the field cookie, you can load the settings through the http, https protocol

If this field is set, it can only be set through the https protocol

2. Local storage

Local storage is a new feature in HTML5, used to solve the problem of insufficient storage space for cookies

1 Overview:

For Web Storage, it is actually an evolution of Cookies storage.

Memorize this mantra: "Two interfaces, four functions".

2. Four functions with two interfaces:

(1) Two interfaces: sessonStorage and localStorage

(2) Four functions: setItem, getItem, removeItem and clear

1.Storage

1.1 Session Storage

Temporary session back session, the time period from page opening to page closing

Temporary storage is to store it, other pages will not be shared

1.2 Local Storage

Safe and permanent storage in the domain. That is, all pages from the same domain name in the client or browser can access localStorage data and the data is permanently saved except for deletion, but the data between the client or browser is independent of each other.

Permanent storage (data can be deleted manually)

Multiple pages can be shared

2. Features of storage

  1. Permanent storage

  2. Storage limit (5M) client micro database

  3. The client completes and does not request server processing

  4. SessionStorage data is not shared, LocalStorage is shared

  5. The browser is not unified and incompatible below IE8

  6. The stored value is limited to string type, which requires us to convert through JSON object

  7. If there is more storage content, the content space will be digested, which will cause the card to change.

3. storage API

3.1 setItem (key name, key value)

Set the data (key, value) type, the types are all strings

Store a string-type data on the local client, where the first parameter "key name" represents the identifier of the data, and the second parameter "key value" is the data itself.

Such as

 localStorage.setItem("name", "hello");

3.2 getItem():

Read the data that has been stored locally, and use the key name as a parameter to read the data of the corresponding key name. Such as: get data, get the corresponding value by key.

Such as:

        localStorage.setItem("name", "hello");
        let c = localStorage.getItem("name");
        console.log(c)

 The printed result is the value of name: hello

3.3 removeItem():

Remove the data that has been stored locally, and delete the data corresponding to the key name by using the key name as a parameter.

Delete data, delete the corresponding value by key

 localStorage.removeItem("name"); 

3.4 clear():

Remove all data stored locally. Delete all stored values.

localStorage.clear(); 

 

4. Case

<body>
    <button id="addData">添加数据</button>
    <button id="getData">获取数据</button>
    <button id="removeData">删除数据</button>
    <button id="clearData">清空数据</button>
    <input type="text" id="txt">
    <script>
        let addBtn = document.querySelector("#addData");
        let getBtn = document.querySelector("#getData");
        let reBtn = document.querySelector("#removeData");
        let clearBtn = document.querySelector("#clearData");
        let txt = document.querySelector("#txt");
        let arr = ['1','2','3'];
        let num = 0;
        //可根据需求切换Session Storage和local Storage
        addBtn.onclick = function () {
            let value = txt.value.trim();
            if(value) {
                sessionStorage.setItem(arr[num], txt.value);
            }
            num++;
            if(num > arr.length - 1) {
                num = 0;
            }
        }
        //获取name名为1的数据
        getBtn.onclick = function() {
            window.alert(sessionStorage.getItem('1'))
        }
        //删除name名为2的数据
        reBtn.onclick = function () {
            sessionStorage.removeItem('2')
        }
        
        clearBtn.onclick = function() {
            sessionStorage.clear();  
        }
    </script>
</body>

In this case, you can test the specific effect of the methods in Session Storage and Local Storage,

Session storage cannot be shared by multiple pages.Data has been added in the current window, and then the data we manually added when it is opened in a new window is no longer visible.

Local Storage can be shared on multiple pages, the data has been added in the current window, and then the data we manually added still exists when it is opened in a new window.

 

发布了34 篇原创文章 · 获赞 145 · 访问量 7192

Guess you like

Origin blog.csdn.net/lhrdlp/article/details/105173802