Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript operating cookies_Basic knowledge

Detailed explanation of JavaScript operating cookies_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:12:261174browse

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: =; both name and value must be legal identifiers.

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:

Copy code The code is as follows:

document.cookie = 'username=Darren';

In the above code, 'username' represents the cookie name, and 'Darren' represents the value corresponding to this name. If the cookie name does not exist, then a new cookie is created; if it exists, the value corresponding to the cookie name is modified. If you want to create cookies multiple times, just use this method repeatedly.

2. Cookie reading operation

It is actually very simple to read cookies accurately, just operate on strings. Copy this code from w3school for analysis:

Copy code The code is as follows:

function getCookie(c_name){
  if (document.cookie.length>0){   //First check whether the cookie is empty, if it is empty, return ""
   c_start=document.cookie.indexOf(c_name "=") //Check whether this cookie exists through the indexOf() of the String object. If it does not exist, it will be -1 
   if (c_start!=-1){
    c_start=c_start c_name.length 1 //The last 1 actually represents the "=" number, so that the starting position of the cookie value is obtained
c_end=document.cookie.indexOf(";",c_start) //Actually, I was a little dizzy when I first saw the second parameter of indexOf(). Later I remembered that it means the specified starting index position...This sentence is for Get the end position of the value. Because we need to consider whether it is the last item, we can judge it by whether the ";" sign exists
    if (c_end==-1) c_end=document.cookie.length 
Return unescape(document.cookie.substring(c_start,c_end)) //The value is obtained through substring(). If you want to understand unescape(), you must first know what escape() does. It is a very important foundation. If you want to know more, you can search. The details of cookie encoding will also be explained at the end of the article
   }
  }
return ""
} 

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:

Copy code The code is as follows:

document.cookie = "name=value;expires=date";

The date value in the above code is a date string in GMT (Greenwich Mean Time) format, and is generated as follows:
Copy code The code is as follows:

var _date = new Date();
_date.setDate(_date.getDate() 30);
_date.toGMTString();

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:

Copy code The code is as follows:

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());
}
//Usage: setCookie('username','Darren',30)

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:

Copy code The code is as follows:

exdate.setHours(exdate.getHours() expiredays);

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:

Copy code The code is as follows:

document.cookie = "name=value;path=path"
document.cookie = "name=value;expires=date;path=path"

The path in red font is the path of the cookie. The most common example is to put the cookie in the directory, so that no matter which sub-page creates the cookie, all pages can access it:

Copy code The code is as follows:

document.cookie = "name=Darren;path=/";

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:

Copy code The code is as follows:

document.cookie = "name=value;path=path;domain=domain";

The red domain is the value of the cookie domain set.

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:

Copy code The code is as follows:

document.cookie = "username=Darren;path=/;domain=qq.com";

Note: It must be access between the same domain. The domain value cannot be set to a domain name other than the primary domain.

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:

Copy code The code is as follows:

document.cookie = "username=Darren;secure"

Setting the cookie to secure only ensures that the data transmission process between the cookie and the server is encrypted, and the cookie file stored locally is not encrypted. If you want local cookies to be encrypted, you have to encrypt the data yourself.

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:

Copy code The code is as follows:

document.cookie = name "=" escape (value);

Let’s look at the sentence inside getCookie() mentioned in the basic usage:

Copy code The code is as follows:

return unescape(document.cookie.substring(c_start,c_end));

This way you don't have to worry about cookie information being incorrect due to special symbols appearing in the cookie value.

Personal Code

Copy code The code is as follows:

/*Set Cookie*/

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn