If there is any mistake, please point it out, thank you very much

Cookie

If you want to test locally, please note:

  1. Can’t passCreate a new HTML and test it inside
  2. Based on number one you might want me to usehttp-serverRun tests,http-serverA pit
  3. Based on the above two, how do I test? 1: Directly test on the console 2: Use the Chrome plug-inWeb Serve

Attach a icon

introduce

An HTTP Cookie (also known as a Web Cookie or browser Cookie) is a small piece of data that a server sends to a user’s browser and keeps locally. It is carried and sent to the server the next time the browser makes a request to the same server. Typically, it is used to tell the server whether two requests are from the same browser, such as to keep the user logged in. Cookies make it possible to record stable state information over stateless HTTP protocols. HTTP protocol itself does not have the function of saving previously sent requests or responses. Although HTTP/1.1 is stateless protocol, Cookie technology is introduced in order to achieve the desired function of maintaining state. (From Graphic HTTP)

Cookies were once used to store data on the client side. As there was no other suitable storage method at that time, cookies were used as the only storage method. However, as modern browsers began to support a variety of storage methods, cookies gradually fell into disuse. Since the Cookie is specified by the server, each browser request carries the Cookie data, incurring additional performance overhead (especially in a mobile environment). New browser apis already allow developers to store data directly locally, such as using the Web storage API (localStorage localStorage and sessionStorage sessionStorage) or IndexedDB.

use

Cookies are mainly used for the following three aspects:

  1. Session state management (such as user login status, shopping cart, game score, or other information that needs to be logged)
  2. Personalization (such as user-defined Settings, themes, etc.)
  3. Browser behavior tracking (e.g. tracking and analyzing user behavior, etc.)

Set up the

// javascript native method to set cookies
document.cookie = "username=DaSheng"; 

function setCookie(cname, cvalue, exdays) {
    var d = new Date(a);// Set the timestamp. Take the current time plus the time to expire. This is measured in minutes, but should actually be measured in days, i.e. a line in the comment
    d.setTime(d.getTime() + (exdays * 60 * 1000));
    // d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    
    // The toGMTstring() call works, but is no longer obsolete.
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
// But the expiration time is not 1 minute. Maybe two or three minutes, but it will definitely expire...

setCookie('sex'.'male'.1) // Set the cookie to expire after 1 minute
console.log(document.cookie) / / sex = male
Copy the code

When setting cookies, there is an expiration time and a default expiration time

  1. document.cookie = "username=DaSheng";This is theDefault expiration time, the default is session level
  2. SetCookie ('sex', 'male ', 1)This one has an expiration date

To obtain

console.log(document.cookie);// username=DaSheng; age=25; Phone =85762XX this is the native method

/ / get a cookie
function getCookie(name){
    const obj = {}
    / / get a cookie
    var cookies = document.cookie
    // Convert a string cookie to an array
    var arr = cookies.split('; ')
    // go through the number group
    arr.forEach(item= > {
        // Get the current key
        const key = item.split('=') [0].trim()
        // Get the current value
        const value = item.split('=') [1]
        // Add to obj
        obj[key] = value
    })
    return obj[name]
}
getCookie('username') // DaSheng
Copy the code

There are two things you can’t get when you get it.

  1. cookieExpired will be directly unavailable
  2. Server SettingsHttpOnlyIs true

delete

/ / remove the cookie
function clearCookie(name) {
    // To clear cookies, just reassign and set the expiration time to -1.
    setCookie(name, "", -1);  
}
Copy the code

expires

Expiration time

  • If the expiration time is set, the system runs according to the set expiration time
  • If no expiration time is set, it is session level

ToUTCString () : **new Date() instanceof Date** If the value is of Date type, you can call.toutcString () to check whether it is of Date type

Domain

The Domain identifier specifies which hosts can accept cookies. If this parameter is not specified, it defaults to the host of the current document (excluding the subdomain name). If Domain is specified, subdomain names are generally included.

document.cookie='username=DsSheng; domain=.baidu.com';
document.cookie='username=DsSheng; domain=.google.com';
Copy the code

The values of the two above are different. One is.baidu.com, one is.google.com.

Obviously, cookies can only be set on the domain. Baidu.com cookies are bound to the domain name, so the above mentioned non-cross-region, that is, cannot be used under different domain names, each cookie will be bound to a single domain name

path

The Path identifier specifies which paths under the host can accept cookies (the URL Path must exist in the request URL). Child paths are also matched with the character %x2F (“/”) as the path separator.

For example, if Path=/docs is set, the following addresses will match:

  • /docs
  • /docs/Web/
  • /docs/Web/HTTP

secure

Cookies are only transmitted by HTTPS (Boolean or NULL).

size

The size of a cookie.

HttpOnly

If set totrue, then the cookie cannot be obtained. To preventMalicious attack (XSS)Photo examples:Acquisition situation:This point if the interview asked how to preventMalicious attacksMay I mention it for a second…

SameSite

Starting with Chrome 51, a SameSite property has been added to the browser’s Cookie to prevent CSRF attacks and user tracking.

The SameSite property of cookies is used to limit third-party cookies to reduce security risks. He has three values

  • Strict
  • Lax
  • None

Strict: Strict is the strictest. Third-party cookies are strictly prohibited. Cookies are not sent across sites under any circumstances. In other words, cookies are carried only if the URL of the current web page matches the target of the request

Lax: The Lax rule is slightly relaxed, and third-party cookies are also not sent in most cases, except for Get requests that navigate to the target url

None: Chrome plans to make Lax the default. At this point, the site can choose to explicitly turn off the SameSite property and set it to None. However, the Secure attribute must be set at the same time (cookies can only be sent through HTTPS). Otherwise, cookies are invalid.

Priority

I can’t read emmmm because I have order

Cookie scope

This is from MDN

The Domain and Path identifiers define the scope of the Cookie: that is, which urls the Cookie should be sent to. The Domain identifier specifies which hosts can accept cookies. If this parameter is not specified, it defaults to the host of the current document (excluding the subdomain name). If Domain is specified, subdomain names are generally included.

For example, if you set Domain=mozilla.org, cookies are also included in the subdomain (e.g. Developer.mozilla.org).

The Path identifier specifies which paths under the host can accept cookies (the URL Path must exist in the request URL). Child paths are also matched with the character %x2F (“/”) as the path separator.

For example, if Path=/docs is set, the following addresses will match:

  • /docs
  • /docs/Web/
  • /docs/Web/HTTP

conclusion

  • key
  • value
  • domain
  • expires
  • secure
  • path

These are things that can be applied to the front end

  • size
  • HttpOnly
  • SameSite
  • Priority

The top ones are controlled by the back end.

Cookie method above

// Set cookie (no expiration time, default callback level)
function setCookie(cname, cvalue, exdays) {
    var d = new Date(a); d.setTime(d.getTime() + (exdays *24 * 60 * 60 * 1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
/ / remove the cookie
function clearCookie(name) {  
    setCookie(name, "", -1);  
}
/ / get a cookie
function getCookie(name){
    const obj = {}
    var cookies = document.cookie
    var arr = cookies.split('; ')
    arr.forEach(item= > {
        const key = item.split('=') [0].trim()
        const value = item.split('=') [1]
        obj[key] = value
    })
    return obj[name]
}
Copy the code

Finally:Originally wanted tocookie localStorage sessionStorageWe wrote it together. Last ordercookieUnconsciously already all afternoonthe

localStorage

LocalStorage is a new feature added by HTML5 to be used as localStorage, which solves the problem of insufficient cookie storage space (the storage space of each cookie is 4k). The size of localStorage is generally supported by the browser is 5M. This will vary between browsers. The life cycle of localStorage is permanent, and the data in localStorage does not disappear after the page or browser is closed. LocalStorage data will never disappear unless it is actively deleted

  • 5 m size
  • Permanent storage (unless manually emptied)
  • Multiple tabs are also common (browser tabs) Require cognate, subdomain names do not take effect

There is also a situation visitgoogleHome, open the console, and selectApplicationTAB, click openlocalStorage, you’ll find three options. Different domain names.

I think, since the three domain name,localStorage is shared? I run it under www.google.com

localStorage.setItem('2'.'2')
Copy the code
  1. inwww.google.comIt can be displayed normally.
  2. inogs.google.comYou can’t see it.

I tried setting it up at ogs.google.com

localStorage.setItem('Subdomain'.'Subdomain')
Copy the code
  1. inogs.google.comIs the normal display.
  2. inwww.google.comIt can also be displayed.

So let’s look at acquisition

localStorage.getItem('Subdomain')
Copy the code
  1. inwww.google.comYou can’t get it.
  2. inogs.google.comIt is normally acquired.

The same goes for deleting and emptying

The author can not think of what application can do, limited to writing business code every day… sorry

sessionStorage

SessionStorage is similar to localStorage, but the life cycle of sessionStorage is only valid for the current session. SessionStorage introduces the concept of a browser window. SessionStorage is data that is always present in same-origin Windows. As long as the browser window is not closed, the data remains even if the page is refreshed or another page is entered. SessionStorage is normally 5M in size, but sessionStorage is destroyed when the browser window is closed. At the same time independently open the same window the same page, sessionStorage is not the same

  • 5 m size
  • Session level (clears by closing the viewer)
  • This does not work if different tabs are the same name.

Note that although not the same TAB can not be retrieved, there is one case, through the a link click jump (need to be the same origin)

To compare

The same

  • Same size (5M)
  • It’s all for storage

The difference between

  • Different life cycles (sessions, versus persistent storage)
  • Different policies (multi-tab case)

advice

For single-page development, operations are routed from one page to another, so sessionStorage is a good fit

  • sessionStorageCan be guaranteed when opening the pagesessionStorageIs null
  • Every time you open a pagelocalStorageIt stores data from the last time the page was opened, so you need to clean up the previous data

usage

1. Check whether the browser supports localStorage/sessionStorage

if (window.localStorage) {
    alsert('Browser support localStorage')}else {
    alert('Browser does not currently support localStorage')}Copy the code

2. LocalStorage and sessionStorage have the same usage, such as setItem(), getItem(), removeItem(), etc

Store the data

Usage: setItem(key, value) code demonstration

localStorage.setItem('key'.'value')
sessionStorage.setItem('key'.'value')
Copy the code

Note The same rules for localStorage as for sessionStorage for arrays and object types

  • Array: [1,2,3] –> 1,2,3
  • Array: [] –> empty
  • Array: [[]] –> empty
  • Array: [[1]] –> 1
  • Array: [true, false] –> true,false
  • [{name: ‘XiaoMing’}] –> [object object]
  • Array: [null,undefined,NaN] –>,,NaN
  • Object: {} –> [object object]
  • {name: ‘XiaoMing’} –> [object object]

If value is a basic type, store it directly. Json.stringify needs to be converted if it is an array (primitive values are fine) and must be converted if it is an object

To get the data

Usage: getItem(key) code demonstration

localStorage.getItem('name')
sessionStorage.getItem('user')
Copy the code

If json.stringify is converted at setup time, json.parse should be converted again at fetch time to get the data we want

Note if the Settings are [1,2,3] –> 1,2,3, we can only get a string of 1,2,3

Modify the data

Modify === Reset

Just call setItem(key,value) again

Delete the data

Usage: removeItem(key) code example

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

Empty data

Usage: clear() Code example

localStorage.clear();
sessionStorage.clear();
Copy the code

Comparison (plus cookies)

Cookie localStorage sessionStorage Cookie localStorage sessionStorage Cookie localStorage sessionStorage Cookie localStorage sessionStorage

The life cycle

Cookie: The expiration time can be set. If the expiration time is not set, the expiration time is closed by default

LocalStorage: will be permanently saved unless manually cleared.

SessionStorage: valid only in the current web session, will be cleared after closing the page or browser.

The size of the

Cookie: about 4KB

LocalStorage: 5MB of information. SessionStorage: same as above.

The HTTP request

Cookies: Are carried in HTTP headers each time. Using cookies to store too much data can cause performance problems.

LocalStorage: stored only in the client (browser) and does not communicate with the server. SessionStorage: same as above.

Ease of use

Cookie: needs to be packaged by the programmer, the cookie interface is not friendly

LocalStorage: the source interface is acceptable and can be reencapsulated to support Object and Array. SessionStorage: same as above

Application scenarios

cookie:

  • Requests are carried automatically, most appropriately through permission authentication at the time of sending the request.
  • Keep the number as small as possible (this varies from browser to browser)
  • security

localStorage:

  • Closing the browser won’t clear it, it’s good for storing some unchanging data,

sessionStorage:

  • Closing the browser clears the data for more sensitive data