Cookie introduction and explanation of Cookie operations in JavaScript

Source: Internet
Author: User
Tags cookie names set cookie
This article briefly introduces the usage and running mechanism of the following cookies, as well as various methods for using JavaScript to operate cookies. The summary is comprehensive and I hope to help you. What is Cookie "cookie is stored in...

This article briefly introduces the usage and running mechanism of the following cookies, as well as various methods for using JavaScript to operate cookies. The summary is comprehensive and I hope to help you.


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:

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:

function getCookie (c_name) {
If (document.cookie.length> 0) {// Query whether the cookie is empty first, return ""
C_start = document.cookie.indexOf (c_name + "=")
// Check whether the cookie exists through the indexOf () of the String object, or -1 if it does not exist
If (c_start! =-1) {
C_start = c_start + c_name.length + 1
// The last +1 actually means "=", so you get the starting position of the cookie value
C_end = document.cookie.indexOf (";", c_start)
其实 // In fact, I just saw the second parameter of indexOf () suddenly became a little dizzy, and later remembered that it indicated the specified starting index position ...
This sentence is to get the end position of the value. Because we need to consider whether it is the last item, we judge by the existence of ";"
If (c_end ==-1) c_end = document.cookie.length
Return unescape (document.cookie.substring (c_start, c_end))
// The value is obtained by substring (). If you want to understand unescape (), you must first know what escape () does. It is an important foundation.
What you want to know can be searched, and the details of cookie encoding will be explained 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:

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:

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:

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:

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 "#" Page. Then, the page under the path "/Darren_code/", for example, "#", can obtain the cookie information.

By default, the cookie cannot be accessed by "#" or "#". (It is useless to look at it. Actually, the truth is "^_^ ).

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

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:

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:

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:

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:

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:

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

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

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

/ * Set Cookies * /
function setCookie (c_name, value, expiredays, path, domain, secure) {
 var exdate = new Date (); // Get the current time
 exdate.setDate (exdate.getDate () + expiredays); // expire 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); // Set whether to encrypt
};
setCookie ('test', 'name = sheng; sex = men; lancer = dullbear', 30);
setCookie ('bb', 'name = sheng; sex = men', 30);
/ * Get Cookies * /
function getCookie (c_name, index) {
 var cookies = document.cookie; // Get cookie value
 var cookieLen = cookies.length; // Get cookie length
 if (cookieLen> 0) {// cookie is not empty
  var c_start = cookies.indexOf (c_name + '='); // Find the number of the cookie value in the cookie
  if (c_start> -1) {// When cookie value exists
   c_start + = c_name.length + 1; // Get cookie value start sequence number
   var c_end = cookies.indexOf (';', c_start); // Get the end value of the cookie value
   if (c_end == -1) {// When cookie is the last one
    c_end = cookieLen; // Set the end value of cookie value to cookie length
   };
   var cookieStr = unescape (cookies.substring (c_start, c_end)); // Get decoded cookie value
   var cookieObj = cookieStr.split (';'); // Split cookie value
   index = ((index == null)? 0: index); // determine whether index is passed by value
   var goalObj = cookieObj [index]; // index array
   var goalStr = goalObj.split ('=');
   var getcook = goalStr [1]; // Get the cookie value
   return getcook;
  };
 } else {
  console.log ('Page has no cookies');
 }
};
alert (getCookie ('test', 0)); // print query cookie value 



The preceding section describes how to use cookies and how to use JavaScript to operate cookies. For more information, see PHP Chinese website (www.php1.cn )!




Related Article

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.