Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript operating cookies_Basic knowledge
What are Cookies
"A cookie is a variable that is stored on the visitor's computer. This cookie is sent each time the same computer requests a page through a browser. You can use JavaScript to create and retrieve the cookie's value." - w3school
A cookie is a file created by a visited website to store browsing information, such as profile information.
From a JavaScript perspective, cookies are just some string information. This information is stored in the client's computer and is used to transfer information between the client computer and the server.
This information can be read or set through document.cookie in JavaScript. Since cookies are mostly used for communication between the client and the server, in addition to JavaScript, server-side languages (such as PHP) can also access cookies.
Cookie Basics
Cookies have a size limit. The data stored in each cookie cannot exceed 4kb. If the length of the cookie string exceeds 4kb, this attribute will return an empty string.
Since cookies are ultimately stored in the client computer in the form of files, it is very convenient to view and modify cookies. This is why it is often said that cookies cannot store important information.
The format of each cookie is like this:
Cookies have an expiration date. By default, the life cycle of a cookie ends when the browser is closed. If you want the cookie to be usable after the browser is closed, you must set a validity period for the cookie, which is the cookie's expiration date.
alert(typeof document.cookie) The result is string. I once thought it was array and made a joke... 囧
Cookies have the concept of domain and path. Domain is the concept of domain. Because the browser is a security-conscious environment, different domains cannot access cookies from each other (of course, cross-domain access to cookies can be achieved through special settings). Path is the concept of routing. A cookie created by a webpage can only be accessed by all webpages in the same directory or subdirectory as this webpage, but cannot be accessed by webpages in other directories (this sentence is a bit confusing, I will look at it later) It’s easier to understand with an example).
In fact, the way to create cookies is somewhat similar to the way to define variables. Both require the use of cookie names and cookie values. The same website can create multiple cookies, and multiple cookies can be stored in the same cookie file.
Cookie FAQ
There are two types of cookies:
Cookies set by the current website you are browsing
Third-party cookies from other domain sources such as embedded ads or images on web pages (websites can track your usage information by using these cookies)
The basic knowledge just mentioned the issue of cookie life cycle. In fact, cookies can be roughly divided into two states:
Temporary cookies. The website will store some of your personal information during current use, and this information will also be deleted from your computer when the browser is closed
Set cookies with expiration time. Even if the browser is closed, this information will still be on the computer. Such as login name and password, so you don't have to log in every time you go to a specific site. This cookie can remain on your computer for days, months or even years
There are two ways to clear cookies:
Clear cookies through browser tools (there are third-party tools, and the browser itself also has this function)
Clear cookies by setting their expiry date
Note: Deleting cookies may sometimes cause some web pages to not function properly
Browsers can be set to accept and deny access to cookies.
For functional and performance reasons, it is recommended to reduce the number of cookies used and try to use small cookies as much as possible.
The details of cookie encoding will be introduced separately in the advanced cookie chapter.
If it is a page on the local disk, the Chrome console cannot use JavaScript to read and write cookies. The solution...change a browser^_^.
Basic usage of cookies
1. Simple access operation
When using JavaScript to access cookies, you must use the cookie attribute of the Document object; a line of code describes how to create and modify a cookie:
2. Cookie reading operation
It is actually very simple to read cookies accurately, just operate on strings. Copy this code from w3school for analysis:
Of course, there are many ways to read cookies, such as arrays, regular expressions, etc., so I won’t go into details here.
3. Set cookie validity period
The life cycle of cookies that often appears in articles is the validity period and expiration period, that is, the existence time of the cookie. By default, cookies are automatically cleared when the browser is closed, but we can set the validity period of the cookie through expires. The syntax is as follows:
The above three lines of code are broken down into several steps:
Generate a Date instance through new to get the current time;
The getDate() method gets a certain day in the current local month, and then adds 30. I hope this cookie can be saved locally for 30 days;
Then set the time through the setDate() method;
Finally, use the toGMTString() method to convert the Date object into a string and return the result
Use the following complete function to illustrate what we need to pay attention to in the process of creating cookies - copied from w3school. Create a function that stores information in a cookie:
Now our function sets the validity time of the cookie according to the number of days. If you want to set it in other units (such as hours), then change the third line of code:
After setting this way, the cookie validity period will be based on hours.
There are two methods to clear cookies mentioned in the FAQ. What we are going to talk about now is to invalidate cookies by setting the validity period to an expired time. Now that there is a way to set the validity period, interested friends are asked to do it themselves ^_^. Let’s continue with the more in-depth topic of cookies.
Cookie Advanced Chapter
1. Cookie path concept
In the basic knowledge, it is mentioned that cookies have the concepts of domain and path. Now let’s introduce the role of path in cookies.
Cookies are generally created when a user visits a page, but this cookie is not only accessible on the page where the cookie is created.
By default, only web pages in the same directory or subdirectory as the page that created the cookie can be accessed. This is due to security considerations, so not all pages can freely access cookies created by other pages. For example:
Create a cookie on the page "http://www.jb51.net/Darren_code/", then the page under the path "/Darren_code/" will be like: "http://www.jb51.net/Darren_code /archive/2011/11/07/Cookie.html" This page can obtain cookie information by default.
By default, "http://www.jb51.net" or "http://www.jb51.net/xxxx/" cannot access this cookie (just looking at it is useless, practice will tell the truth) ^_^).
So how to make this cookie accessible to other directories or parent directories can be achieved by setting the path of the cookie. Examples are as follows:
2. Cookie domain concept
Path can solve the problem of accessing cookies in the same domain. Let’s go on to talk about the problem of cookies realizing access between the same domains. The syntax is as follows:
For example, "www.qq.com" and "sports.qq.com" share an associated domain name "qq.com". If we want the cookie under "sports.qq.com" to be "www.qq. com" to access, we need to use the domain attribute of the cookie, and set the path attribute to "/". Example:
3. Cookie security
Usually cookie information uses HTTP connections to transfer data. This transfer method is easy to view, so the information stored in cookies is easy to steal. If the content passed in the cookie is important, encrypted data transmission is required.
So the name of this attribute of cookie is "secure", and the default value is empty. If the attribute of a cookie is secure, then data is transferred between it and the server through HTTPS or other secure protocols. The syntax is as follows:
Note: Even if the secure attribute is set, it does not mean that others cannot see the cookie information saved locally on your machine, so in the final analysis, just don’t put important information in cookies, 囧...
4. Cookie encoding details
Originally I wanted to introduce the knowledge of cookie encoding in the FAQ section, because if you don’t understand this, the encoding problem is indeed a pitfall, so I’ll explain it in detail.
When entering cookie information, special symbols such as spaces, semicolons, and commas cannot be included. In general, cookie information is stored in an unencoded manner. Therefore, before setting the cookie information, you must first use the escape() function to encode the cookie value information, and then use the unescape() function to convert the value back when the cookie value is obtained. For example, when setting cookies:
Personal Code
function setCookie(c_name, value, expiredays, path, domain, secure) {
var exdate = new Date(); //Get the current time
exdate.setDate(exdate.getDate() expiredays); //Expiration time
document.cookie = c_name "=" //cookie name
escape(value) //Encode cookie value
((expiredays == null) ? "" : ";expires=" exdate.toGMTString()) //Set expiration time
((path == null) ? '/' : ';path=' path) //Set the access path
((domain == null) ? '' : ';domain=' domain) //Set the access domain
((secure == null) ? '' : ';secure=' secure); //Set whether to encrypt
};
setCookie('test', 'name=sheng;sex=men;lancer=dullbear', 30);
setCookie('bb', 'name=sheng;sex=men', 30);
/*Get Cookie*/
function getCookie(c_name, index) {
var cookies = document.cookie; //Get cookie value
var cookieLen = cookies.length; //Get cookie length
if (cookieLen > 0) { //When cookie is not empty
var c_start = cookies.indexOf(c_name '='); //Find the cookie value and the serial number in the cookie
if (c_start > -1) { //When cookie value exists
c_start = c_name.length 1; //Get the cookie value starting sequence number
var c_end = cookies.indexOf(';', c_start); //Get cookie value end sequence number
If (c_end == -1) { //When the cookie is the last one
c_end = cookieLen; //Set the cookie value end sequence number to the cookie length
};
var cookieStr = unescape(cookies.substring(c_start, c_end)); //Get the decoded cookie value
var cookieObj = cookieStr.split(';'); //Split cookie value
index = ((index == null) ? 0 : index); // Determine whether index is passed a value
var goalObj = cookieObj[index]; //index array
var goalStr = goalObj.split('=');
var getcook = goalStr[1]; //Get the required cookie value
Return getcook;
};
} else {
Console.log('Page has no cookies');
}
};
alert(getCookie('test', 0)); //Print query cookie value