I will send my resume to you. I have been working on gay foundation recently, and I have made a continuously updated Github note. You can go and have a look at it. Front-End-Basics

The address of this article: Three local storage methods

Github address for basic Notes: github.com/qiqihaobenb… , can be watch, can also be star.


The body begins…


Three local storage options

cookie

preface

One of the biggest problems in the early days of the web was managing state. In short, the server has no way of knowing whether two requests are coming from the same browser. The easiest way back then was to insert some parameters into the page at request time and pass them back on the next request. This requires using a hidden form with parameters, or passing it as part of the URL parameters. Both solutions are manual and error-prone. Cookies come in to solve this problem.

role

Cookies are plain text and have no executable code. Store data. When users visit a website (webpage), we can store data on visitors’ computers through cookies, or the data (usually encrypted) stored on users’ local terminals by some websites for identifying users’ identities and session tracking.

How to work

When a web page sends an HTTP request, the browser checks whether there is a cookie and automatically adds it to the cookie field in the Request header. This is what the browser does automatically for us, and it does it for us every time we make an HTTP request. This feature is important because it relates to what kind of data is appropriate to store in cookies.

The data stored in cookies will be automatically placed in HTTP requests by the browser every time. If these data are not sent to the server in every request, the automatic processing of the browser will undoubtedly increase the network overhead. However, if the data is the data that needs to be sent to the server on each request (such as authentication information), the browser’s automatic processing of this setting greatly reduces the need to add data repeatedly. Therefore, cookies are especially suitable for setting “information to be carried on every request (most typically authentication information)”, while other types of data are not suitable.

Characteristics of the

  1. Different browsers store cookies in different locations and cannot be used universally.
  2. Cookie storage is distinguished in the form of domain names. Cookies stored in different domains are independent.
  3. We can set the domain in which the cookie takes effect (the subdomain of the domain in which the cookie is currently set), that is, the cookies we can operate on are the current domain and all subdomains under the current domain
  4. The number of cookies that can be stored in a domain name is limited. The number of cookies that can be stored in a domain name varies with different browsers. Generally, the number is 20.
  5. There is also a limit on the size of each cookie. Different browsers store different cookie sizes, generally 4KB.
  6. Cookies can also be set to expire at the end of the session by default, and will be automatically destroyed when the time expires

Cookie values can be set and read.

Set up the

Client Setup

Document. cookie = 'name = value '; document.cookie = 'username=cfangxu; Domain=baike.baidu.com 'and set the valid domainCopy the code

Note: Clients can set the following cookie options: Expires, Domain, PATH, secure (conditional: secure cookies can only be set in HTTPS web pages), but cannot set the HttpOnly option.

Server-side Settings Whether you request a resource file (such as HTML/JS/CSS/image) or send an Ajax request, the server will return a response. In response header, there is an item called set-cookie, which is specially used by the server to set cookies.

The set-cookie header is a string of the following format (the part in parentheses is optional) : set-cookie: value[; Expires =date][; domain=domain][; path=path][; Secure]Copy the code

Note: only one set-cookie field can be set. If you want to set multiple cookies, you need to add the same number of set-cookie fields. The server can Set all the options for the cookie: Expires, Domain, PATH, Secure, HttpOnly The options specified by set-cookie are only used on the browser side and are not sent to the server side.

read

Cookie is a string value that contains all cookies from the current web site (to avoid cross-domain scripting (XSS) attacks, this method can only fetch non-HTTPOnly cookies). It concatenates all cookies with a semicolon + space, for example username=chenfangxu; job=coding

Modify the cookie

To modify a cookie, you simply reassign and the old value is overwritten by the new value. Note, however, that when setting new cookies, the path/domain options must remain the same as the old cookie. Otherwise, the old value is not modified, but a new cookie is added.

delete

Set the expiration time of the cookie to the past time. The path/domain/ options must remain the same as the old cookie.

Pay attention to

If only one value is set, then the value in the cookie is counted; If two cookies are set with the same key value, the one below overwrites the one above.

Properties of cookie (optional)

Expiration time

If we want to store a cookie for a long time. The cookie needs to be set to expire at the same time. If not set, cookies are stored temporarily by default and destroyed automatically when the browser closes the process

Note: document.cookie = 'name = value; Expires =' + GMT date string;Copy the code

New Date().setDate(odate.getDate () + 5); 5 days more than the current time

An example of setting cookie timeliness

function setCookie(c_name, value, expiredays){ var exdate=new Date(); exdate.setDate(exdate.getDate() + expiredays); document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" :"; Expires ="+ exdate.togmtString ())} setCookie('username','cfangxu',30)Copy the code

Expires is an option in HTTP /1.0. In the new HTTP /1.1 protocol, expires has been replaced by max-age, both of which limit how long a cookie can last. The expires value is a point in time (cookie expiration = expires), while the max-age value is a time period in seconds (cookie expiration = creation + max-age).


In addition, the default value of max-age is -1(that is, the validity period is session); Max-age has three possible values: negative, 0, and positive.


Negative: validity period session;


0: deletes cookies.


Positive: The validity period is creation time + max-age

Domain concept for cookies (Domain option)

Domain specifies which domain or domains cookies will be sent to. By default, domain is set to the domain of the page that created the cookie, so the cookie is sent to the server when a request is made to the same domain.

The browser does a tail comparison (starting at the end of the string) between the value of the domain and the requested domain name, and sends matching cookies to the server.

Client Setup

document.cookie = “username=cfangxu; path=/; Domain=qq.com “as above: “www.qq.com” shares a related domain name “qq.com” with “sports.qq.com”. If we want the cookies under “sports.qq.com” to be accessed by “www.qq.com”, We need to use the domain property of the cookie, and we need to set the path property to “/”.

Server Settings

Set-Cookie: username=cfangxu; path=/; Note: The value of domain must be inter-domain access. You cannot set domain to a non-primary domain name.

Cookie path concept (Path option)

Cookies are generally created because the user visits the page, but not only on the page that created the cookie can access the cookie. For security reasons, by default, only web pages that are in the same directory or subdirectory as the page that created the cookie are accessible. That is, the path property can specify cookies for server-specific documents. The url set by this property and the URL path with this prefix are valid.

Client Setup

The most common example is to have cookies in the root directory, so that no matter which child page creates the cookie, all pages can access it.

document.cookie = "username=cfangxu; path=/"

Server Settings

Set-Cookie:name=cfangxu; path=/blog

The path option will match /blog, /blogrool, etc. Any option that begins with /blog is valid. Note that the path attribute is compared only after the Domain option is verified. The default value of the path attribute is the PATH part of the URL to which the set-cookie header is sent.

Domain and PATH summary:

Domain is the domain name and path is the path. Together, they form the URL. Domain and Path restrict which urls cookies can be accessed. So the domain and pathoptions together determine when the cookie is automatically added to the request header by the browser and sent out. If these two options are not set, the default values are used. The default value of domain is the domain name of the web page where the cookie is set, and the default value of path is the directory where the cookie is set.

Cookie security (Secure option)

Generally, cookie information is transmitted through HTTP connections, which is easy to be checked, so the information stored in cookies is easy to be stolen. If what is passed in the cookie is important, then encrypted data transfer is required.

The secure option is used to set cookies to be sent only on secure requests. Cookies with the Secure option can be sent to the server only when the request is HTTPS or other security protocol.

document.cookie = "username=cfangxu; secure"

If cookie is set to Secure, only data transmission between cookie and server is encrypted, but the local cookie file is not encrypted. Even if you set the secure property, it does not mean that others cannot see the cookies stored locally on your machine. Confidential and sensitive information should never be stored or transmitted in cookies because the entire mechanism of cookies is inherently insecure

Note: If you want to set secure cookies on the client side, i.e. the web page, through JS, you must ensure that the web page is HTTPS protocol. Cookies of the secure type cannot be set on HTTP web pages.

httpOnly

This option sets whether cookies can be accessed through JS. By default, cookies do not have the httpOnly option (i.e. empty), so by default, clients can access (including reading, modifying, deleting, etc.) this cookie through JS code. When the cookie has the httpOnly option, the client cannot access (including reading, modifying, deleting, etc.) the cookie through JS code.

HttpOnly cookies cannot be set by javascript on the client side. This type of cookie can only be set by the server side.

Cookie coding

Cookie is actually a string, but the string is treated as a special character. Therefore, when the key and value of cookies contain these three special characters, additional encoding is required. Escape is generally used for encoding, and unescape is used for decoding when reading cookies. Of course you can also use encodeURIComponent/decodeURIComponent or encodeURI/decodeURI, check the information about the coding

Third party cookies

Usually the cookie’s field matches the browser address’s field, which is called a first-party cookie. The third-party cookie is the cookie whose field does not match the field in the address bar. This kind of cookie is usually used in third-party advertising websites. In order to track the browsing history of users, and according to the collection of users’ browsing habits, push relevant advertisements to users. Questions about the safety of the third party cookies and cookie can view mp.weixin.qq.com/s/oOGIuJCpl…

  • Cookie Recommendation Resources

    • Talk about the cookie
    • HTTP cookies,


localStorage

HTML5 new approach, but compatible with IE8 and above.

The characteristics of

  • Life cycle: Persistent local storage that never expires unless it is actively deleted.
  • Stored information is shared within the same domain.
  • When you add, modify, or delete localStorage on this page, this page will not trigger the storage event, but other pages will trigger the storage event.
  • Size: said to be 5M (depending on browser vendor)
  • It can be opened locally in non-IE browsing. The Internet Explorer browser must be opened on the server.
  • LocalStorage is essentially a string read. If you store too much content, memory space will be consumed and pages will become jammed
  • LocalStorage is restricted by the same Origin policy

Set up the

localStorage.setItem('username','cfangxu');

To obtain

Localstorage.getitem (‘username’) can also get the key name localstorage.getitem (‘username’

delete

Localstorage.remove (‘username’) also clears all storage localstorage.clear ()

Storage events

Triggered when the storage changes. The event callback function has a parameter event, which is a StorageEvent object and provides some useful properties, as shown in the following table:

Property Type Description
key String The named key that was added, removed, or moddified
oldValue Any The previous value(now overwritten), or null if a new item was added
newValue Any The new value, or null if an item was added
url/uri String The page that called the method that triggered this change


sessionStorage

In fact, similar to localStorage, also localStorage, session localStorage

Features:

  • Used to store data in a session locally, which can only be accessed by pages in the same session and is destroyed when the session ends. Therefore, sessionStorage is not a persistent local storage, only session level storage. This means that as long as the browser window is not closed, the data will still exist even if the page is refreshed or another page is entered. After closing the window, sessionStorage will be destroyed, or open another page of the same origin in a new window, sessionStorage is also not.


Cookie, localStorage, sessionStorage difference

  • Same: Stores data locally (browser side)
  • Different:

    LocalStorage and sessionStorage

    As long as localStorage uses the same protocol, host name, and port, it can read/modify the same localStorage data.

    SessionStorage is more stringent than localStorage. In addition to protocol, host name, port, sessionStorage also requires the same window (that is, the browser TAB).

    LocalStorage is permanent unless manually deleted.

    SessionStorage When the session ends (automatically destroyed when the current page is closed)

    Cookie data will be sent to the server every time the HTTP request is sent, but localStorage and sessionStorage will not.