Cookie operations in JavaScript _ basic knowledge-js tutorial

Source: Internet
Author: User
Tags cookie names set cookie
This article describes how to operate cookies in JavaScript, this article describes what are cookies, basic Cookie knowledge, common Cookie problems, two methods for clearing cookies, basic Cookie usage, and advanced cookie usage. For more information, see What is Cookie?

"Cookie is a variable stored on the visitor's computer. This cookie is sent every time a computer requests a page through a browser. You can use JavaScript to create and retrieve cookie values ." -W3school

A cookie is a file created on a visited website. It is used to store browsing information, such as personal information.

From the JavaScript perspective, cookies are strings. This information is stored in the client computer and used to transmit information between the client computer and the server.

In JavaScript, you can use document. cookie to read or set this information. Because cookies are mostly used for communication between the client and the server, in addition to JavaScript, the server language (such as PHP) can also access cookies.

Basic Cookie knowledge

A cookie has a size limit. Each cookie cannot store more than 4 kb of data. If the cookie string length exceeds 4 kb, this attribute returns an empty string.

Because cookies are stored in the client computer as files, it is convenient to view and modify cookies. This is why Cookies cannot store important information.

The format of each cookie is as follows: = <值> ; Names and values must both be valid identifiers.

Cookie is valid. By default, the lifecycle of a cookie ends when the browser is closed. If you want to use a cookie after it is disabled by the browser, you must set a validity period for the cookie, that is, the expiration date of the cookie.

Alert (typeof document. cookie) returns a string. I used to think it was an array and made a joke... Bytes

Cookie has the concept of domain and path. Domain is the concept of domain. Because browsers are secure environments, different domains cannot access each other's cookies (of course, cross-origin cookie access 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 the webpage, it cannot be accessed by web pages in other directories (this sentence is a bit difficult, so I will understand it after looking at an example later ).

In fact, the method for creating a cookie is similar to that for defining a variable. Both cookie names and cookie values are required. Multiple cookies can be created for the same website, and multiple cookies can be stored in the same cookie file.

Cookie FAQs

There are two types of cookies:

The cookie set for the current website you are browsing

Third-party cookies from other domain sources such as advertisements or Images embedded on webpages (websites can use these cookies to track your usage information)

As mentioned in the basic knowledge, the cookie lifecycle can be roughly divided into two statuses:

Temporary cookies. During the current use process, the website will store some of your personal information. When the browser is closed, the information will be deleted from the computer.

Set the cookie with the expiration time. Even if the browser is closed, the information industry will still be in the computer. Such as the logon name and password, you do not need to log on to a specific site each time. This cookie can be retained on a computer for several days, months, or even years.

There are two methods to clear cookies:

Clear cookies using browser Tools (with third-party tools, the browser also has this function)

Clear the cookie by setting the cookie Validity Period

Note: deleting a cookie may cause some webpages to fail to run normally.

The browser can accept and reject access cookies through settings.

For functional and performance reasons, we recommend that you reduce the number of cookies and use small cookies whenever possible.

Details about cookie encoding will be discussed separately in the cookie advanced section.

For a page on a local disk, the chrome console cannot use JavaScript to read and write cookies. solution... Change to another browser ^_^.

Basic Cookie usage

1. Simple access operations

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:

The Code is as follows:


Document. cookie = 'username = darren ';


In the above Code, 'username' indicates the cookie name, And 'darren' indicates the value corresponding to this name. If the cookie name does not exist, a new cookie is created. If the cookie name exists, the corresponding value is modified. If you want to create a cookie multiple times, repeat this method.

Ii. cookie reading

To precisely read cookies, it is actually very easy to perform operations on strings. Copy this code from w3school for analysis:

The Code is as follows:


Function getCookie (c_name ){
If (document. cookie. length> 0) {// first query whether the cookie is null. if it is null, return ""
C_start = document. cookie. indexOf (c_name + "=") // use the indexOf () of the String object to check whether the cookie exists. If it does not exist, it is-1.
If (c_start! =-1 ){
C_start = c_start + c_name.length + 1 // The last + 1 actually represents the "=" number, so that the start position of the cookie value is obtained.
C_end = document. cookie. indexOf (";", c_start) // In fact, when I first saw the second indexOf () parameter, I suddenly felt a little dizzy. Later I remembered that it represented the specified start index position... this is to get the end position of the value. Because you need to consider whether it is the last item, you can determine whether the ";" number exists.
If (c_end =-1) c_end = document. cookie. length
Return unescape (document. cookie. substring (c_start, c_end) // obtain the value through substring. It is an important foundation to know what escape () is. If you want to know more about it, you can search for the cookie encoding details at the end of the article.
}
}
Return ""
}

 

Of course there are still many methods to read cookies, such as arrays and regular expressions. I will not elaborate on them here.

3. Set the cookie Validity Period

In this article, the life cycle of the cookie, that is, the validity period and expiration period, that is, the time when the cookie exists. By default, cookies are automatically cleared when the browser is closed, but we can use expires to set the cookie validity period. Syntax:

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. The generation method is as follows:

The Code is as follows:


Var _ date = new Date ();
_ Date. setDate (_ date. getDate () + 30 );
_ Date. toGMTString ();

The above three lines of code are divided into several steps:

Generate a Date instance using new to get the current time;

The getDate () method is used to obtain a day in the current local month. Then, 30 is added, which means that the cookie can be saved locally for 30 days;

The setDate () method is used to set the time;

Finally, the toGMTString () method is used to convert the Date object to a string and return the result.

The following complete function is used to describe what we need to pay attention to when creating cookies-copied from w3school. Create a function to store information in cookies:

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, we use this function to set the cookie validity period based on the number of days. If you want to set it in another unit (such as hour), you can change the third line of code:

The Code is as follows:


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

In this way, the cookie validity period is calculated on an hourly basis.

I have mentioned two methods to clear a cookie. Now I want to disable the cookie by setting the validity period to an expiration time. Now that you have a method to set the validity period, you can set the failure period. Next we will continue to talk about cookie topics.

Cookie advanced

1. cookie Path Concept

I have mentioned in the basic knowledge that cookie has the concept of domain and path. Now I will introduce the role of path in cookie.

Generally, a cookie is created because the user accesses the page. However, the cookie is not accessible only on the page where the cookie is created.

By default, only webpages in the same directory or subdirectory as the page for cookie creation can be accessed. This is because of security considerations, not all pages can access the cookies created on other pages at will. For example:

Create a cookie on the "http://www.jb51.net/darren_code/" page. Then, the page in the"/Darren_code/"path is shown as" the token can obtain the cookie information.

By default, the cookie cannot be accessed by "http://www.jb51.net" or "http://www.jb51.net/xxxx ).

So how to make this cookie accessible to other directories or parent directories can be achieved by setting the cookie Path. Example:

The Code is as follows:


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


The path in the red font is the cookie path. The most common example is to keep the cookie in the directory. In this way, no matter which sub-page the cookie is created, all the pages can be accessed:

The Code is as follows:


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

Ii. cookie domain concept

The path can solve the problem of cookie access in the same domain. Let's talk about the problem of cookie access between the same domain. Syntax:

The Code is as follows:


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


The red domain is the set cookie domain value.

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 accessed by "www.qq.com, we need to use the domain attribute of the cookie and set the path attribute to "/". Example:

The Code is as follows:


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


Note: It must be the access between the same domain. The domain value cannot be set as a domain name of a non-primary domain.

Iii. cookie Security

Generally, cookie information is transmitted through an HTTP connection. This transmission method is easy to view, so the information stored in cookies is easily stolen. If the content transmitted in cookies is important, encrypted data transmission is required.

Therefore, the name of the cookie attribute is "secure" and the default value is null. If the attribute of a cookie is secure, data is transmitted between the cookie and the server over HTTPS or other security protocols. Syntax:

The Code is as follows:


Document. cookie = "username = Darren; secure"


Setting the cookie as secure only ensures that the data transmission process between the cookie and the server is encrypted, while the cookie files stored locally are not encrypted. If you want to encrypt the local cookie, you must encrypt the data yourself.

Note: even if the secure attribute is set, it does not mean that others cannot see the cookie information stored locally on your machine. Therefore, in the end, do not put the important information in the cookie...

Iv. cookie encoding details

I originally wanted to introduce the knowledge of cookie encoding in the FAQ section, because if I don't know about it, the encoding problem is indeed a pitfall, so I 'd like to explain it in detail.

When entering cookie information, it cannot contain spaces, semicolons, commas, and other special characters. In general, the storage of cookie information is not encoded. Therefore, before setting cookie information, you must use the escape () function to encode the cookie value information and use the unescape () function to convert the value when obtaining the cookie value. For example, when setting a cookie:

The Code is as follows:


Document. cookie = name + "=" + escape (value );


Let's take a look at the getCookie () mentioned in the basic usage:

The Code is as follows:


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


In this way, you do not have to worry about cookie Information errors due to special characters in the cookie value.

Personal Code

The Code is as follows:


/* Set Cookie */

Function setCookie (c_name, value, expiredays, path, domain, secure ){
Var exdate = new Date (); // obtain the current time
Exdate. setDate (exdate. getDate () + expiredays); // expiration time
Document. cookie = c_name + "=" + // cookie name
Escape (value) + // encode the cookie value
(Expiredays = null )? "": "; Expires =" + exdate. toGMTString () + // set the expiration time
(Path = null )? '/': '; Path =' + path) + // set the access path
(Domain = null )? '': '; Domain =' + domain) + // set the access domain
(Secure = null )? '': '; Secure =' + secure); // sets 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; // obtain the cookie value
Var cookieLen = cookies. length; // obtain the cookie length.
If (cookieLen> 0) {// when the cookie is not empty

Var c_start = cookies. indexOf (c_name + '='); // you can specify the cookie value in the cookie.
If (c_start>-1) {// when the cookie value exists
C_start + = c_name.length + 1; // obtain the start serial number of the cookie value

Var c_end = cookies. indexOf (';', c_start); // obtain the end serial number of the cookie value.
If (c_end =-1) {// when the cookie is the last
C_end = cookieLen; // set the end serial number of the cookie value to the cookie length.
};

Var cookieStr = unescape (cookies. substring (c_start, c_end); // get the decoded cookie value

Var cookieObj = cookieStr. split (';'); // split the cookie value

Index = (index = null )? 0: index); // determines whether the index is passed

Var goalObj = cookieObj [index]; // index Array
Var goalStr = goalObj. split ('= ');
Var getcook = goalStr [1]; // obtain the cookie value.
Return getcook;
};
} Else {
Console. log ('no cookies on the page ');
}
};

Alert (getCookie ('test', 0); // print the query cookie value

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.