JavaScript Cookie Operation detailed

Source: Internet
Author: User
Tags current time getdate parent directory setcookie

Cookie Base Usage

A. Simple access operation

When using JavaScript to access cookies, you must use the cookie property of the Document object; a line of code describes how to create and modify a cookie:

  

The code is as follows Copy Code
Document.cookie = ' Username=darren '

In the above code ' username ' denotes the cookie name, ' Darren ' indicates the value of the name. Assuming that the cookie name does not exist, create a new cookie, or modify the value of the cookie name if it exists. If you want to create a cookie multiple times, use this method repeatedly.

Two. read operation of Cookies

The exact way to read a cookie is simply to manipulate the string. Copy this code from the W3school to do the analysis:

  code is as follows copy code
function GetCookie (c_name) {
if (document.cookie.length>0) {///First query whether the cookie is empty, return ""
C_start=document.cookie.indexof (c_name + "=")//through the String object's IndexOf () to check whether the cookie exists, does not exist 1
if (c_start!=-1) {
C_start=c_start + c_name.length+1//finally this +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 IndexOf () the second parameter when suddenly a bit dizzy, then remembered to indicate the location of the specified start index ... This sentence is to get the end position of the value. Because of the need to consider whether the last one, so through the ";" Whether the number exists to judge
if (c_end==-1) c_end=document.cookie.length
Return unescape (document.cookie.substring (c_start,c_end))//Gets the value through substring (). To understand Unescape () is to know what escape () is to do, are very important basis, want to understand the search can be, at the end of the article will also explain the cookie coding details
}
}
Return ""
}

Of course, there are a number of ways to read cookies, such as arrays, and so on, here is not to elaborate.

Three. Set the expiration date of the cookie

The life cycle of the cookie that often appears in the article is the period of validity and expiration, that is, the existence time of the cookie. By default, cookies are automatically cleared when the browser is closed, but we can set the expiration date of the cookie by expires. The syntax is as follows:

The code is as follows Copy Code

Document.cookie = "Name=value;expires=date"

The date-type string in the preceding code, in GMT (GMT) format, is generated as follows:

The code is as follows Copy Code

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 the day of the current local month, plus 30 is what I want the cookie to be stored locally for 30 days;

Then the Setdate () method is used to set the time;

Finally, the date object is converted to a string using the toGMTString () method, and the result is returned

Here's a complete function to illustrate what we need to be aware of in creating cookies-copied from W3school. To create a function that stores information in a cookie:

The code is as follows Copy Code

1 function Setcookie (c_name, value, Expiredays) {
2 var exdate=new Date ();
3 Exdate.setdate (exdate.getdate () + expiredays);
4 Document.cookie=c_name+ "=" + Escape (value) + ((expiredays==null)? "": "; expires=" +exdate.togmtstring ());
5}
6 Methods of Use: Setcookie (' username ', ' Darren ', 30)

Now our function is to set the valid 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:

Exdate.sethours (exdate.gethours () + expiredays);

After this setting, the cookie validity period is in hours.

There are two ways to get rid of cookies in common problems, but now it's time to disable the cookie by setting the expiration date to an expired time. Now that there is a way to set the expiration date, then the method of setting the expiration period invites interested friends to do their own ^_^. Below continue the deeper cookie topic.

Cookie Advanced Article


A. Cookie path concept

In the basics, there is a reference to the notion that a cookie has a domain and a path, now to describe the path's role in the cookie.

Cookies are typically created by the user accessing the page, but not only on the page where the cookie is created.

By default, only pages that are in the same directory or subdirectory as the page in which the cookie was created are accessible because of security considerations that do not allow all pages to freely access cookies created by other pages. As an example:

To create a cookie on the "http://www.111cn.net/school/" page, the page under the "/school/" path, such as "http://www.111cn.net", will be able to get cookie information by default.

By default, "Http://www.111cn.net" or "http://www.111cn.net/xxxx/" can not access this cookie (the light is useless, practice truth ^_^).

So how to get this cookie to be accessed by other directory or parent directory Access class, by setting the path of the cookie can be implemented. Examples are as follows:

  

The code is as follows Copy Code
Document.cookie = "Name=value;path=path"
Document.cookie = "Name=value;expires=date;path=path"

The red type path is the path to the cookie, and the most common example is to have the cookie in the directory, so that no matter which child page created the cookie, all pages can be accessed:

The code is as follows Copy Code

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

Two. cookie Domain concept

The path solves the problem of accessing cookies under the same domain, and we go on to say that cookies implement the problem of accessing the same domain. The syntax is as follows:

 

The code is as follows Copy Code
Document.cookie = "Name=value;path=path;domain=domain"

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

For example, "www.qq.com" and "sports.qq.com" common an associated domain name "qq.com", if we want to "sports.qq.com" cookies under "www.qq.com" access, we need to use cookies Domain attribute, and you need to set the Path property to "/". Cases:

The code is as follows Copy Code

Document.cookie = "username=darren;path=/;d omain=qq.com"

Note: A certain is the access between the same domain, you can not set the value of domain to the domain name of the non-primary domain.

Three. Cookie Security

Cookie information is usually used to pass data using an HTTP connection, which can be easily viewed, so cookies store information that is easily stolen. If the content passed in the cookie is more important, then the encrypted data transfer is required.

So the name of this property for the cookie is "secure," and the default value is null. If the property of a cookie is secure, it communicates data between the server via HTTPS or another security protocol. The syntax is as follows:

The code is as follows Copy Code

Document.cookie = "Username=darren;secure"

Setting the cookie to secure only guarantees that the data transfer process between the cookie and the server is encrypted, while the locally stored cookie file is not encrypted. If you want to encrypt the local cookie, 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 that is stored locally on your machine, so in the final analysis, don't put the important information on the cookie,??..

Four. Cookie coding details

Originally wanted to introduce the cookie code knowledge in the FAQ section, because if you don't know the coding problem is really a pit, so say it in detail.

When you enter cookie information, you cannot include spaces, semicolons, commas, and other special symbols, and in general, the storage of cookie information is in a way that is not encoded. So, before setting cookie information, use the escape () function to encode the cookie value information, and then use the unescape () function to convert the value back when the cookie is worth the time. When setting cookies:

The code is as follows Copy Code

Document.cookie = name + "=" + Escape (value)

Take a look at the phrase in GetCookie () mentioned in the basic usage:

The code is as follows Copy Code

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

This doesn't have to worry because there is a special symbol in the cookie value that causes the cookie information to go wrong.

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.