An article takes you to understand front-end cookies



1. Preface (some nonsense)

I believe that everyone who clicks on this article should be familiar with browser cookies. It is a very important content in the front-end field. Of course, it is also a test point for interviews. I wonder if you really have mastered cookies? Of course not. It doesn't matter if you master it. You can follow the steps of the editor to learn about front-end cookies. Those who are not familiar with it may have a new understanding of browser cookies after reading this article.

PS: What I am talking about here is the front-end cookies, not the cookies in the back-end field. If you like it enough, you can consider writing an article about the back-end.

2. Cookies

1. Why are there cookies?

Web applications use the HTTP protocol to transmit data. However, the HTTP protocol is a stateless protocol. Once the data exchange is completed, the connection between the client and the server will be closed, and a new connection needs to be established to exchange data again. This means that the server cannot track the session from the connection.
You may have such an experience that when you log in to a website, it will remind you whether to remember the account and password, so that you don't have to enter the account and password again next time. This is the role of cookies. When we visit again, it is convenient for the server to directly fetch the last visited things directly according to our cookies (for each cookie server, it will store the data we took last time for this cookie, and the next For the same cookie at a time, just fetch it here.

2. Characteristics of cookies

When the server receives an HTTP request, the server can set a Set-cookie option in the response header, and the browser will automatically save the cookie after receiving the response, and then the browser will pass the cookie to the server in each request to the server. The information is sent to the server, which is where the cookie comes from.
Of course, there are also restrictions on the number and size of cookies in browsers. The size is generally 4k. The number of cookies is different for each browser. You can refer to the table below.

FF Chrome Safari Opera IE7.0/8.0
Number of cookies 50 per domain 53 per domain no limit 30 per domain name 50 per domain name
cookie size 4097 bytes 4097 bytes 4097 bytes 4096 bytes 4095 bytes

It is worth noting that the information stored in the cookie is not safe (important information cannot be stored), there are concepts of domain and path in the cookie, and the browser is a relatively safe environment, so different domains cannot be directly accessed (js Same-origin policy restrictions)
PS : But because each request of the browser will carry a cookie, which will bring additional overhead, and the storage capacity is relatively small, so the browser later launched a new API (web stoeage Api and indexedDb)

3. Browser cookies

Open the developer tools of the browser, and you can see the cookies stored in the current browser in the [Application] tab, as shown in the figure below.
insert image description here
The meaning of the field name:

  • Name: the name of the cookie (key)
  • Value: the value stored in the cookie
  • Expires: Refers to the time when the cookie expires (this time is the world time UTC time), also known as Greenwich Mean Time
  • Max-Age: refers to the maximum survival period of the cookie (unit: second)
  • Domain: Refers to the current domain of the cookie
  • Path: Refers to the current path of the cookie
  • Size: Refers to the size of the cookie storage
  • Secure: Refers to the security attribute of cooke

4. Cross-site and cross-domain

Cross-site and cross-domain are necessary knowledge for understanding cookies

definition example
cross domain As long as one of the "protocol + host name + port" of the two URLs is inconsistent, it is cross-domain http://www.taobao.com/ and https://www.taobao.com/
Cross Station The eTLD+1 of the two URLs is not the same a.github.io and b.github.io
eTLD effective top level domain (effective top level domain name) .com、.co.uk、.github.io
eTLD+1 Effective top-level domain name + second-level domain name taobao.com

Therefore, as long as the top-level domain name and the second-level domain name are the same
insert image description here
, they are on the same site. To give two examples, a.com and b.com are cross-site, while aacom and bacom belong to the same site, because the second-level domain name and the top-level domain name are the same, The detailed explanation of cross-domain will not be expanded here. If there are many likes, the editor may consider writing a related article later.

3. Cookie operation

1. Get cookies

You can enter in the browser console document.cookieto get part of the cookie information stored in the mark of the current website.
What is obtained is a string of strings, and the serialization method is: k1=v1;k2=v2;k3=v3 Why do you
insert image description here
say that only part of the cookies are obtained, because as long as the js with HttpOnly ticked cannot be obtained and operated, this kind of Cookies can only be operated by the server and the browser. Usually, these cookies are used to store some user identity information or security-related credentials. You
insert image description here
can use the following code to store cookies in an object

function deal(){
    
     var cookie = document.cookie;
var arr = cookie.split('; ');//注意是 分号空格
var obj = {
    
    };
    arr.forEach(function(item){
    
    
       var itemArr = item.split('=');
       obj[itemArr[0]] = itemArr[1];
})
    return obj;
}

2. Set cookies

Setting cookies in the browser is also done document.cookiethrough , storing cookies to the browser in the form of key-value pairs
insert image description here
, you can see that the setting has been successful
insert image description here

3. Modify cookies

It is also very simple to change and modify the cookies that have been stored in the browser. You can use it document.cookieto operate. Just reassign the value of the same key to modify the stored cookie value. You
insert image description here
can see that the update is successful.
insert image description here

4. Delete cookies

Deleting the value of the cookie is also very simple, or use document.cookieto operate, you only need to empty the key corresponding to the cookie to be deleted, and then add the value of max-age to -1 and
insert image description here
the cookie will disappear after execution

4. Cookie attributes

1. Cookie attribute Domain

Domain is used to set the address of the host that the cookie can act on, and it does not carry the protocol and port when it is stored in the browser. Because different ports and protocols will not affect cookies, but some attributes of cookies can only be valid under Https, which is also one of the characteristics of cookies 不区分协议和端口.
If there is a .baidu.con in the front, it proves that the current cookie can be applied to the current domain and its subdomains. If the following cookie is accessible in niuma.baidu.com and there is no such cookie in front of it in niuma It cannot be accessed in .baidu.com and can only be accessed in baidu.com.
insert image description here
If the Domain attribute is not set when setting the cookie, the cookie can only be applied to the current domain.
One thing to note is that the domain attribute is set when the cookie is set, and
insert image description here
the place where the browser stores the cookie turns out to be .uicool123.com?? ? This is a place worthy of everyone's attention.
insert image description here
When setting domain=.uicool123.com, it is still the same as the above situation, that is to say, the setting methods of the two doamin attributes are the same.
There is one last point worth noting about the domain, that is, you can set cookies for the parent domain in the subdomain.
For example, if we set cookies in niu.uicool123.com, and the doamin attribute is set to .uicool123.com, then we can get it in uicool123.com This cookie can also be obtained in hhh.uicool123.com because this cookie is applied to uicool123.com and its subdomains.
But we can't set cookies in the subdomain of the current domain or across domains. For example, when we set cookies in the console of uicool123.com, the domain attribute cannot be set to hhh.uicool123.com or baidu.com

2. Cookie attribute path

The path of the cookie is used to specify the path of the URL.
insert image description here
If we set the following cookie in the console of a.com/a

document.cookie='myname=牛马;path=/a'

Then as long as the prefix is ​​a.com/a, this cookie can be accessed under the path, such as a.com/a/b/c a.com/a/b,
but it cannot be accessed under the path whose prefix is ​​not a.com/a The attribute of this cookie, such as a.com/b a.com/b/a,
is used less, and it is generally set to /path

3. Cookie attribute expires

The expires attribute is used to set the attributes related to the validity period of the cookie. expires specifies the specific time when the cookie expires
注意: when it exists at the same time as the max-age attribute, the priority of max-age will be higher
insert image description here
. 10 expired cookies

document.cookie=`myname=牛马;expires=${
      
      new Date('2022-11-26 01:10:00').toUTCString()}`

insert image description here
It can be seen that
insert image description here
the expires attribute can also be set to the past time. After it takes effect, the browser will delete this cookie immediately.
When a cookie contains neither expires nor max-age attribute, then this cookie is a session cookie , this cookie will be automatically deleted when you close the browser, and it will not be deleted when you refresh and close the current page.

4. Cookie attribute max-age

The max-age attribute is also used to set the attributes related to the validity period of Cookie. max-age specifies the number of seconds before the cookie expires.
insert image description here
For example, we set a cookie that expires after 600 seconds

document.cookie=`myname=牛马;max-age=600`

insert image description here
It can be seen that the setting is successful
insert image description here
注意: when the expires and max-age attributes are both set, the max-age setting will take precedence. If the max-age is set to a negative value, the cookie will be deleted. When
a cookie contains neither expires nor the max-age attribute Then, this cookie is a session cookie, which will be automatically deleted when you close the browser, and will not be deleted when you refresh and close the current page.

5. Cookie attribute httponly

httponly is a cookie closely related to cookie security, which is also mentioned above.
As long as the HttpOnly ticked js cannot be obtained and operated, this kind of cookie can only be operated by the server and browser. Usually, this kind of cookie is used to store some user identity information or security-related credentials.
insert image description here
This kind of cookie can only be set through the server response.
insert image description here
When the browser sets the cookie with this attribute, the cookie will be directly ignored by the browser.
insert image description here

5. Cookie attribute secure

The secure attribute is used to tell the browser that this cookie can only be transmitted using the https protocol. If the response from the server contains a cookie with the secure attribute, but the current protocol is http, the browser will directly ignore this cookie
. Create an attribute with secure
insert image description here
, then when we make a request to https://a.com, we will carry this cookie,
but when we request http://a.com, we will not carry this cookie

6. Cookie attribute samesite

Regarding samesite, this is an attribute that changes a lot. The samesite attribute can limit the sending of cookies when cross-site requests are made. There are three values ​​of samesite

samesite attribute value effect
None Send cookies regardless of cross-site
Lax Send Cookie in the case of some cross-site requests (default value)
Strict Do not send cookies across sites

insert image description here
Regarding the cookie whose samesite attribute is None, although the binding force is the weakest, the browser considers it valid only when the cookie is transmitted by the HTTPS protocol. In addition, the cookie must be added with the secure attribute, otherwise it cannot be saved.
We can create 4 cookies
insert image description here
insert image description here
to see that the browser does not automatically add lax when the samesite attribute is not set.
When requesting the same domain address, these 4 cookies will be brought.
Note: samesite will only work when cross-site requests

5. Ending

Finally, there are a few cookie attributes that are not commonly used. I won’t go into details. Interested friends can search for related articles by themselves. If there are any mistakes in the article, readers and friends can point them out in the comment area. Thank you for reading.

Guess you like

Origin blog.csdn.net/Siebert_Angers/article/details/127986794