This is the 27th day of my participation in the August Genwen Challenge.More challenges in August

There are three methods to implement localStorage in JavaScript: sessionStorage, localStorage, and cookie

1.cookie

A Cookie is a small piece of text data no more than 4KB, consisting of a Name, a Value, and several other optional attributes used to control the validity, security, and scope of the Cookie.

Cookie mechanism: If the expiration time is not set in the browser, the cookie is stored in memory and its life cycle ends when the browser closes. This cookie is referred to as session cookie. If a cookie expiration time is set in the browser, the cookie is saved in the hard disk. After the browser is closed, the cookie data still exists until the expiration time ends

When the Web server sends a Web page to the browser, the server does not record the user’s information after the connection is closed. The purpose of cookies is to solve the problem of “how to record user information on the client “:

  • When a user visits a Web page, his name can be recorded in a cookie.
  • The user’s access record can be read in the cookie the next time the user visits the page.

That way you don’t need to enter a password when you jump from one page to another

Create a cookie

    document.cookie="username=John Doe";
    
    / / read cookies
    var x = document.cookie;
Copy the code

2. The sessionStorage and localStorage

The difference between sessionStorage and localStorage is that the data stored in the browser does not disappear when you close the web page, and they can hold 5 meters or more of data

Data in sessionStorage will be cleared when you close the page to hold temporary data, while data in localStorage will not be cleared unless you manually delete it

Method of use

Save data syntax:

localStorage.setItem("key", "value");

sessionStorage.setItem("key", "value");
Copy the code

Syntax for reading data:

var lastname = localStorage.getItem("key");

var lastname = sessionStorage.getItem("key");
Copy the code

Delete data syntax:

localStorage.removeItem("key");
sessionStorage.removeItem("key");
Copy the code

Clear all data:

sessionStorage.clear()
Copy the code

The advantages of webStorage

  1. More storage: Cookies are 4KB and WebStorage is 5MB
  2. More secure

3. More convenient to query and use 4. Save network requests