Use of document. Cookie

Source: Internet
Author: User
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 CGI or similar files that are more advanced than HTML, Program But JavaScript also provides comprehensive access rights to cookies.

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

Each cookie is like this: <cookie name >=< value>

The <cookie Name> restriction is similar to the Javascript naming restriction, with the addition of "cannot use JavaScript keywords" and "can only use characters that can be used in URL encoding" missing ". 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 <value> 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.

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.