Use of document. cookie in JavaScript

Source: Internet
Author: User
Tags set cookie
We already know that there is a cookie attribute in the document Object. But what is Cookie? Some Web sites store some information with small text files on your hard disk. These files are called cookies. & Mdash; MSIE help. In general, Coo... SyntaxHighlighter. all

We already know that there is a cookie attribute in the document Object. But what is Cookie? "Some websites store some information on your hard disk with small text files, which are called cookies ." -- MSIE help. In general, Cookies are created by CGI or similar files and programs that are more advanced than HTML, but javascript also provides comprehensive access rights to Cookies.

First, we need to learn the basic knowledge of cookies.

Each Cookie is like this: = <值>

The restriction is similar to the naming restriction of javascript, with the addition of "cannot use javascript keywords" and "can only be used in URL encoding ". The latter is hard to understand, but as long as you only use letters and numbers for naming, there is no problem at all. <值> The requirement is "only characters that can be used in URL encoding ".

Each Cookie has an expiration date. Once the computer clock expires, the Cookie will be deleted. You cannot delete a Cookie directly, but you can delete it indirectly by setting the expiration date earlier than the current time.

Each webpage, or site, has its own Cookies. These Cookies can only be accessed by webpages under the site, from webpages in other sites or in unauthorized areas under the same site, is inaccessible. Each "group" Cookie has a specified total size (about 2 kb per "group"). If the total size exceeds the maximum size, the first invalid Cookie is deleted first, to make the new Cookie "home ".

Now let's learn how to use the documents. cookie attribute.

If you directly use documents. cookie attribute, or use some method, such as assigning values to variables to obtain documents. cookie value, we can know the number of Cookies in the current document, the name of each cookie, and its value. For example, add "document. write (documents. cookie)" to a document. The result is as follows:

Name = kevin; email = kevin@kevin.com; lastvisited=index.html

This means that the document contains three Cookies: name, email, and lastvisited, whose values are kevin, kevin@kevin.com, and index.html. We can see that two Cookies are separated by semicolons and spaces, so we can use cookieString. the split (';') method returns an array separated by each Cookie (var cookieString = documents first. cookie ).

The method for setting a Cookie is to assign values to documents. cookie. Unlike the assignment in other cases, assigning values to the Cookies. cookie does not delete the original Cookies, but only adds or modifies the original Cookies. Assignment format:

Events. cookie = 'cookiename = '+ escape ('cookievalue') + '; expires =' + expirationDateObj. toGMTString ();

Are you dizzy? CookieName indicates the Cookie name, cookievalue indicates the Cookie value, and expirationDateObj indicates the date object name storing the expiration date. If you do not need to specify the expiration date, the second row is not required. If no expiration date is specified, the browser expires after the browser is closed (that is, all windows are closed) by default.

First, the escape () method: Why must it be used? Because the Cookie value must be "only characters that can be used in URL encoding ". We know that the "escape ()" method is to encode the string by URL encoding, then we only need to use an "escape ()" method to process the value output to the Cookie, you can use "scape SCAPE ()" to process the values received from cookies. The most common use of these two methods is to process Cookies. In fact, setting a Cookie is only "events. cookie = 'cookiename = cookievalue '"is so simple, but it is better to use an escape () to avoid any characters in the URL in cookievalue.

Then the semicolon before "expires" is noted. It is a semicolon rather than a semicolon.

Finally, toGMTString () method: Set the Cookie's validity period date to use the GMT format, and other formats of time do not work.

Now let's take a look. Set a Cookie named "name = rose" and expire three months later.

Var expires = new Date ();
Expires. setTime (expires. getTime () + 3*30*24*60*60*1000 );
/* Three months x one month treated as 30 days x 24 hours a day
X hour 60 Minutes x minute 60 seconds x second 1000 ms */
Documents. cookie = 'name = rose; expires = '+ expires. toGMTString ();

Why not use the escape () method? This is because we know that rose is a legal URL encoded string, that is, 'Rose '= escape ('Rose '). Generally, if you do not use escape () when setting a Cookie, you do not need to use unescape () when obtaining the Cookie ().

Next time: Write a function to find the value of the specified Cookie.

Function getCookie (cookieName ){
Var cookieString = documents. cookie;
Var start = cookieString. indexOf (cookieName + '= ');
// The reason for adding the equal sign is to avoid having
// The same string as cookieName.
If (start =-1) // cannot be found
Return null;
Start + = cookieName. length + 1;
Var end = cookieString. indexOf (';', start );
If (end =-1) return unescape (cookieString. substring (start ));
Return unescape (cookieString. substring (start, end ));
}

This function uses some methods of the string object. If you do not remember (Are you so unremembered), please check it out. All the if Statements of this function do not contain the else. This is because if the condition is true, the program runs the return statement, and the operation stops when the return statement is run in the function, so it's okay if you don't add else. When this function finds the Cookie, it will return the Cookie value; otherwise, "null" is returned ".

Now we want to delete the name = rose Cookie we just set.

Var expires = new Date ();
Expires. setTime (expires. getTime ()-1 );
Documents. cookie = 'name = rose; expires = '+ expires. toGMTString ();

As you can see, you only need to change the expiration date to a little earlier than the current date (this is 1 millisecond earlier), and then set the Cookie in the same way to delete the Cookie.

A js cookie operation function written by a foreigner


 
01
/// Set cookie
02
Function setCookie (NameOfCookie, value, expiredays)
03
{
04
// @ Parameter: three variables are used to set the new cookie:
05
// Cookie name, stored Cookie value,
06
// And the Cookie expiration time.
07
// These rows convert the number of days to a valid date.
08
 
09
Var ExpireDate = new Date ();
10
ExpireDate. setTime (ExpireDate. getTime () + (expiredays * 24*3600*1000 ));
11
 
12
// The following line is used to store cookies. You only need to assign values to "document. cookie.
13
// Note that the date is converted to the GMT time by using the toGMTstring () function.
14
 
15
Document. cookie = NameOfCookie + "=" + escape (value) +
16
(Expiredays = null )? "": "; Expires =" + ExpireDate. toGMTString ());
17
}
18
 
19
/// Obtain the cookie value
20
Function getCookie (NameOfCookie)
21
{
22
 
23
// First, check whether the cookie exists.
24
// If the cookie does not exist, the document. cookie length is 0.
25
 
26
If (document. cookie. length> 0)
27
{
28
 
29
// Check whether the cookie name exists in document. cookie.
30
 
31
// Because more than one cookie value is stored, even if the length of document. cookie is not 0, the cookie with the name we want cannot exist.
32
// So we need this step to check whether the cookie we want exists.
33
// If the begin variable is worth-1, it indicates that it does not exist.
34
 
35
Begin = document. cookie. indexOf (NameOfCookie + "= ");
36
If (begin! =-1)
37
{
38
 
39
// Indicates that our cookie exists.
40
 
41
Begin + = NameOfCookie. length + 1; // the initial position of the cookie value
42
End = document. cookie. indexOf (";", begin); // end position
43
If (end =-1) end = document. cookie. length; // No; end indicates the end position of the string.
44
Return unescape (document. cookie. substring (begin, end ));}
45
}
46
 
47
Return null;
48
 
49
// If the cookie does not exist, null is returned.
50
}
51
 
52
/// Delete a cookie
53
Function delCookie (NameOfCookie)
54
{
55
// Check whether the cookie is set. If so, adjust the expiration time to the past time;
56
// Leave the cookie to the operating system for proper time.
57
 
58
If (getCookie (NameOfCookie) {www.2cto.com
59
Document. cookie = NameOfCookie + "=" +
60
"; Expires = Thu, 01-Jan-70 00:00:01 GMT ";
61
}
62
}
Author: nydia

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.