Gossip JavaScript and cookies

Source: Internet
Author: User

Using cookies we already know that there is a cookie attribute in the Document object. But what is a Cookie? "Some Web sites store information on your hard disk with very small text files, which are called cookies. "--msie help. In general, cookies are CGI or similar, created with higher-level HTML files, programs, and so on, but JavaScript also provides full access to cookies. Tieling County Civil Service Bureau

Before we go on, we need to learn the basics of cookies first.

Every Cookie is like this: <cookie >=< value >.

The limitations of the <cookie name > are much the same as the JavaScript naming restrictions, with fewer "Cannot use JavaScript keywords" and more "only characters that can be used in URL encoding". The latter is difficult to understand, but as long as you name only with letters and numbers, there is no problem at all. The < value > requirement is also "only use characters that can be used in URL encoding."

Each cookie has an expiration date, and once the computer's clock has expired, the cookie is deleted. We cannot delete a Cookie directly, but we can delete it indirectly by setting the expiration date earlier than the current time.

Each Web page, or every site, has its own cookies, which can only be accessed by the Web pages under this site, and pages from other sites or unauthorized areas under the same site are inaccessible. Each "group" of cookies has a specified total size (approximately 2KB per "group"), one exceeds the maximum total size, then the first expired cookie is first deleted to allow the new cookie to "settle".

Now let's learn to use the Document.cookie property.

If you use the Document.cookie property directly, or, in some way, such as assigning a value to a variable, to get the value of Document.cookie, we can know how many cookies, each cookie's name, and its value are in the current document. For example, add "document.write (Document.cookie)" to a document and the results show:

Name=kevin; [Email protected]; Lastvisited=index.html

This means that the document contains 3 Cookies:name, email and lastvisited, and their values are Kevin, [email protected] and index.html. As you can see, the two Cookies are separated by a semicolon and a space, so we can use Cookiestring.split ('; ') method to get an array separated by each Cookie (first with var cookiestring = Document.cookie).

The way to set a Cookie is to assign a value to Document.cookie. Unlike other assignments, assigning a value to Document.cookie does not delete the original cookies, but only adds cookies or changes to the original cookie. Format of assignment:

Document.cookie = ' cookiename= ' + Escape (' cookievalue ') + '; expires= ' + expirationdateobj.togmtstring ();

Did you see the dizziness? The above is not a bold word in the place is to copy not mistaken, bold word is to make changes according to the actual situation. CookieName represents the name of the cookie, Cookievalue represents the value of the cookie, Expirationdateobj represents the date object name that stores the expiration date, and if no expiration date is required, the second line is not required. Without specifying an expiration date, the browser defaults to expire after closing the browser (that is, closing all windows).

Did you see some of the underscores above? These are the places to be noticed.

First Escape () method: Why must you use it? Because the value of the Cookie requires "only characters that can be used in URL encoding". We know that the "escape ()" method encodes the string as a URL encoding, so we only need to use an "escape ()" method to process the output to the cookie value, and "unescape ()" To handle the value received from the cookie is foolproof. And the most common use of these two methods is to process Cookies. In fact, setting a Cookie is just "document.cookie = ' cookiename=cookievalue '" is so simple, but in order to avoid appearing in the Cookievalue URL is not allowed to appear in the characters, or with an escape () good.

Then the semicolon in front of "expires": just notice. is a semicolon and not the other.

Last toGMTString () method: Setting the age of the Cookie is in GMT format, the time in other formats is not useful.

Now let's do the actual combat. Set a "Name=rose" Cookie that expires after 3 months.

var expires = new Date (); Expires.settime (Expires.gettime () + 3 * 30 * 24 * 60 * 60 * 1000); /*   Three months x one months as 30 days x Day 24 hours    x one hour 60 minutes x one minute 60 seconds X one second 1000 milliseconds * * document.cookie = ' name=rose;expires= ' + expir Es.togmtstring ();

Why is the escape () method not used? This is because we know that Rose is a valid URL-encoded string, which means ' rose ' = = Escape (' Rose '). In general, if you do not use escape () when setting a cookie, you do not need to unescape () to get a cookie.

One more time: Write a function that looks for the value of the specified Cookie.

function GetCookie (cookiename) {   var cookiestring = document.cookie;   var start = Cookiestring.indexof (cookiename + ' = ');   The reason for the equals sign is to avoid having the   same string as CookieName in the value of some cookies.   if (start = =-1)//Cannot find     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 of the methods of the string object, if you do not remember (you are not so memory AH), please go to check. All of the IF statements in this function are not with else, because if the condition is true, the program is running the return statement, and the return is encountered in the function, it will terminate the operation, so it is no problem to add else. When the function finds a cookie, it returns the value of the cookie, otherwise it returns "null". Now we want to delete the Name=rose Cookie we just set.

var expires = new Date (); Expires.settime (Expires.gettime ()-1); Document.cookie = ' name=rose;expires= ' + expires.togmtstring ();

As you can see, you just need to change the expiration date to one o'clock (this is 1 milliseconds earlier), and then set the cookie in the same way that you can erase the cookie.

About automatic deletion: In fact, it is not really what is said to delete in a timely manner, for example, you save a cookie, the browser can use this cookie to check whether the cookie expires, if it expires deleted. or the browser timed check, whether there is an expired cookie, and then deleted.

Gossip JavaScript and cookies

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.