JavaScript in Document.cookie

Source: Internet
Author: User

"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.

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".

Set cookies
Each cookie is a name/value pair, and you can assign a string such as the following to Document.cookie: document.cookie= "userid=828";
If you want to store more than one name/value pair at a time, you can use a semicolon plus a space (; ) separated, for example:
Document.cookie= "userid=828; Username=hulk ";
You cannot use a semicolon (;), a comma (,), an equal sign (=), and a space in the name or value of a cookie. It is easy to do this in the name of the cookie, but the value to be saved is indeterminate. How do you store these values? The method is encoded with the escape () function, which can use hexadecimal notation for some special symbols, such as spaces that will be encoded as "20%", which can be stored in cookie values, and the use of this scheme can also avoid the occurrence of Chinese garbled characters. For example:
Document.cookie= "str=" +escape ("I love Ajax");
Equivalent:
Document.cookie= "Str=i%20love%20ajax";
When the Escape () code is used, the unescape () is used to decode the value after it is removed to obtain the original cookie value, in general, if the cookie is set without escape (), then the cookie is not unescape ().

This is already described in the previous article.
Although Document.cookie looks like a property, you can assign different values. However, unlike the general properties, changing its assignment does not mean losing the original value, such as executing the following two statements consecutively:
Document.cookie= "userid=828";
Document.cookie= "Username=hulk";
At this point the browser will maintain two cookies, namely UserID and username, so give document.cookie a value like executing a statement like this:
Document.addcookie ("userid=828");
Document.addcookie ("Username=hulk");
In fact, the browser is in this way to set the cookie, if you want to change the value of a cookie, simply re-assign the value, for example:
Document.cookie= "userid=929";
This sets the cookie value named UserID to 929.

Get the value of a cookie
Here's how to get the value of a cookie. The value of a cookie can be obtained directly from Document.cookie:
var Strcookie=document.cookie;
this will get a string of multiple name/value pairs separated by semicolons that includes all cookies under that domain name . For example:

<script language= "JavaScript" type= "Text/javascript" ><!--document.cookie= "userid=828"; Document.cookie= "Username=hulk"; var strcookie=Document.cookie;alert (Strcookie); // -</script>

you can only get all the cookie values at once, rather than specifying a cookie name to get the specified value, which is the most troublesome part of handling cookie values. The user must parse the string himself to get the specified cookie value, for example, to get the value of the UserID, this can be done:

<script language= "JavaScript" type= "Text/javascript" ><!--//set two cookiesDocument.cookie= "userid=828";d Ocument.cookie= "Username=hulk";//Get Cookie StringvarStrcookie=Document.cookie;//cutting Multi-Cookie into multiple name/value pairsvarArrcookie=strcookie.split (";");varuserId;//iterate through the cookie array and process each cookie against for(vari=0;i<arrcookie.length;i++){             varArr=arrcookie[i].split ("="); //find the cookie with the name UserID and return its value             if("UserId" ==arr[0]) {userId=arr[1];  Break; }}alert (userId);// -</script>

This gives the value of a single cookie in a similar way, you can get the value of one or more cookies, and the main technique is still related to string and array operations.

Set end date for cookies
Until now, all cookies are single-session cookies, which will be lost after the browser is closed, in fact Some cookies are stored in memory only, and no corresponding hard disk files are created.
In real-world development, cookies often require long-term preservation, such as saving the user's login status. This can be accomplished with the following options:
Document.cookie= "userid=828; Expires=gmt_string ";
Where gmt_string is the time string in GMT format, this statement is to set the UserID this cookie to gmt_string represents the expiration time, over this time, the cookie will disappear, inaccessible. For example: If you want to set the cookie to expire after 10 days, you can do so:

<script language= "JavaScript" type= "Text/javascript" ><!--// get current time var date= New Date (); var expiredays=10; // set date to 10 days after the time Date.settime (Date.gettime () +expiredays*24*3600*1000); // set the UserId and username two cookies to expire after 10 days document.cookie= "userid=828; Username=hulk; Expire= "+date.togmtstring (); // -</script>

Delete Cookies
In order to delete a cookie, you can set its expiration time to a past time, for example:

<script language= "JavaScript" type= "Text/javascript" ><!--// get current time var date= New Date (); // sets date to the past time Date.settime (Date.gettime () -10000); // Remove the userId from this cookie document.cookie= "userid=828; Expire= "+date.togmtstring (); // -</script>

Specify the path to an accessible cookie

By default, if a cookie is created on a page, the cookie is also accessible to other pages in the same directory as the page . If there are subdirectories under this directory, they can also be accessed in subdirectories. For example, inwww.xxxx.com/html/a.htmlThe cookie created in the www.xxxx.com/html/b.html can bewww.xxx.com/ html/ Some/c.html is visited, but cannot be www.xxxx.com/d.html access.
in order to control which directories the cookie can access, you need to use the path parameter to set the cookie with the following syntax:
document.cookie= "name=value; Path=cookiedir";
Where Cookiedir represents the directory in which cookies can be accessed. For example:
document.cookie= "userid=320; path=/shop";
means that the current cookie can only be used in the shop directory.
If you want to make the cookie available under the entire Web site, you can specify Cookie_dir as the root directory, for example:
document.cookie= "userid=320; path=/";

Specifies the host name of the accessible cookie
similar to paths, host names refer to different hosts under the same domain, for example: www.google.com and gmail.google.com are two different host names. By default, a cookie created in one host cannot be accessed under another host, but it can be controlled through the domain parameter in the syntax format:
document.cookie= "Name=value; domain= Cookiedomain ";
Take Google as an example, to achieve cross-host access, can be written as:
document.cookie= "name=value;domain=.google.com";
This allows the cookie to be accessed by all hosts under Google.com.

Composite example: Constructing a common cookie handler function
the process of cookie processing is more complicated and has some similarity. Therefore, several functions can be defined to complete the common operation of the cookie , thus implementing the code reuse. The following is a list of commonly used cookie operations and their function implementations.
1. Add a Cookie:addcookie (name,value,expirehours)
The function receives 3 parameters: The cookie name, the cookie value, and the number of hours after which it expires. There is no expiration time when the expirehours is 0, i.e. the cookie disappears automatically when the browser is closed. The function is implemented as follows:

<script language= "JavaScript" type= "Text/javascript" ><!--functionAddcookie (name,value,expirehours) {varCookiestring=name+ "=" +Escape (value); //determine if the expiration time is set     if(expirehours>0){          varDate=NewDate (); Date.settime (Date.gettime+expirehours*3600*1000); Cookiestring=cookiestring+ "; Expire= "+date.togmtstring (); } document.cookie=cookiestring;}// -</script>

2. Gets the cookie value for the specified name: GetCookie (name)
The function returns a cookie value named name, or null if it does not exist, with the following implementation:

<script language= "JavaScript" type= "Text/javascript" ><!--functionGetCookie (name) {varStrcookie=Document.cookie; varArrcookie=strcookie.split (";");  for(vari=0;i<arrcookie.length;i++){         varArr=arrcookie[i].split ("="); if(Arr[0]==name)returnArr[1]; }     return"";}// -</script>

3. Delete Cookie:deletecookie (name) of the specified name
The function can delete a cookie with the specified name, which is implemented as follows:

<script language= "JavaScript" type= "Text/javascript" ><!--function  Deletecookie (name) {               var date=New  date ();              Date.settime (Date.gettime ()-10000);              Document.cookie=name+ "=V; Expire= "+date.togmtstring ();} // -</script>

This article turns from http://javacrazyer.iteye.com/blog/748986

JavaScript in Document.cookie

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.