JavaScript Settings Cookie

Source: Internet
Author: User
Tags time limit
JavaScript Settings Cookie

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 semicolons (;), commas (,), Equals (=), and spaces in the name or value of a cookie. Do it in the name of the cookie

This is easy to do, but the value to be saved is indeterminate. How to store these values. The method is encoded with the escape () function, which can be used to represent some special symbols in hexadecimal notation, for example, the spaces will be encoded as "20%" so that they can be stored in the

Cookie value, and the use of this scheme can also avoid the appearance of Chinese garbled. For example:
Document.cookie= "str=" +escape ("I love Ajax");
Equivalent:
Document.cookie= "Str=i%20love%20ajax";
When you use Escape () encoding, you need to use unescape () to decode after the value is fetched to get the original cookie value.

Although Document.cookie looks like an attribute, it can be assigned a different value. 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";
The browser will maintain two cookies, respectively UserID and username, so give the document.cookie a value like executing a statement similar to this:
Document.addcookie ("userid=828");
Document.addcookie ("Username=hulk");
In fact, the browser is the way to set cookies, if you want to change the value of a cookie, you just have to reassign the value, for example:
Document.cookie= "userid=929";
This sets the cookie value named UserID to 929.

get the value of a cookie
The following describes how to get the value of a cookie. The value of a cookie can be obtained directly by Document.cookie:
var Strcookie=document.cookie;
This will get a string of multiple name/value pairs separated by semicolons that include all cookies under that domain name

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

Name to get the specified value, which is the most troublesome part of handling cookie values. The user must parse this string himself to get the specified cookie value, for example, to get the value of the UserID, which can be achieved by:

<script language= "JavaScript" type= "Text/javascript" >
<!--
Set two cookies
Document.cookie= "userid=828";
Document.cookie= "Username=hulk";
Get cookie String
var Strcookie=document.cookie;
Cut multiple cookies to multiple name/value pairs
var arrcookie=strcookie.split (";");
var userId;
Iterate through the cookie array, processing each cookie on the
for (Var i=0;i<arrcookie.length;i++) {
var arr=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>

In a similar way, you can get the value of one or more cookies, and the main trick is still the related operations of strings and arrays.

set expiration date for cookie
Until now, all cookies are a single session cookie, that is, the cookies will be lost after the browser is closed, in fact these cookies are only stored in memory, but not the corresponding hard disk files.
In actual development, cookies often need to be saved for long periods of time, 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 a time string in GMT format, this statement is to set the UserID cookie to

The expiration time that gmt_string represents, beyond which the cookie disappears and is inaccessible. For example, if you want the cookie

When set to expire after 10 days, this can be achieved:

<script language= "JavaScript" type= "Text/javascript" >
<!--
Get current time
var date=new date ();
var expiredays=10;
Set date to 10 days later
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
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 ();
Set Date to past time

Date.settime (Date.gettime ()-10000);
Remove UserID This cookie

Document.cookie= "userid=828; Expire= "+date.togmtstring ();
-->
</script>

specify the path to the cookie that can be accessed
By default, if a cookie is created on a page, other pages in the same directory as the page can also access the cookie. If there are subdirectories under this directory, they can also be accessed in subdirectories. For example in

Cookies created in the www.xxxx.com/html/a.html can be www.xxxx.com/html/b.html or

Www.xxx.com/html/some/c.html, but cannot be accessed by www.xxxx.com/d.html.
To control which directories a cookie can access, you need to set the cookie using the path parameter, which is the following syntax:
Document.cookie= "Name=value; Path=cookiedir ";
Where Cookiedir represents a directory that can access cookies. For example:
Document.cookie= "userid=320; Path=/shop ";
means that the current cookie can only be used in the shop directory.
If you want the cookie to be available throughout the Web site, you can designate Cookie_dir as the root directory, for example:
Document.cookie= "userid=320; path=/";


Specifies the host name that can access the cookie
Like a path, a host name refers to a different host 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 by the domain parameter in the form of the following syntax:
Document.cookie= "Name=value; Domain=cookiedomain ";
Take Google, for example, to achieve cross host access, which can be written as:
Document.cookie= "name=value;domain=.google.com";
In this way, the cookie is accessible to all hosts under Google.com.


Comprehensive example: Constructing a generic cookie handler function
The processing of cookies is more complex and has a certain similarity. So you can define a few functions to complete the cookie's generic

Operation, which enables the reuse of code. The common cookie actions and their function implementations are listed below.
1. Add a Cookie:addcookie (name,value,expirehours)
The function receives 3 parameters: The cookie name, the cookie value, and how many hours after the expiration. This Convention does not set the expiration time when the expirehours is 0, that is, the cookie disappears automatically when the browser closes. This function is implemented as follows:

<script language= "JavaScript" type= "Text/javascript" >
<!--
function Addcookie (name,value,expirehours) {
var cookiestring=name+ "=" +escape (value);
Determine whether to set an expiration time


if (expirehours>0) {
var date=new date ();
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 and, if it does not exist, returns NULL, which is implemented as follows:

<script language= "JavaScript" type= "Text/javascript" >
<!--
function GetCookie (name) {
var Strcookie=document.cookie;
var arrcookie=strcookie.split (";");
for (Var i=0;i<arrcookie.length;i++) {
var arr=arrcookie[i].split ("=");
if (Arr[0]==name) return arr[1];
}
Return "";
}
-->

function GetCookie (cookie_name) {
var results = Document.cookie.match (' (^|;)? ' + cookie_name + ' = ([^;] *)(;|$)');

if (results)
Return (Unescape (results[2]));
Else
return null;
}
</script>

3. Deletes the 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>


We already know that there is a cookie attribute in the Document object. But what is a Cookie. "Some Web sites store information in very small text files on your hard disk, which is called cookies." "--msie help. In general, cookies are CGI or similar, created in a way that is more than HTML advanced files, programs, and so on, but JavaScript also provides a full range of access rights to cookies.

We need to learn the basics of cookies first.

This is true for each Cookie: <cookie name >=< value >

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

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

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

Now let's learn to use the Documents.cookie attribute.

If you use the Documents.cookie property directly, or, for example, assign a value to a variable to get the value of a documents.cookie, we know how many cookies are in the current document, the name of each cookie, and its value. For example, adding "document.write (Documents.cookie)" To a document shows:

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

This means that the document contains 3 Cookies:name, email and lastvisited, and their values are Kevin, kevin@kevin.com and Index.html respectively. As you can see, two Cookies are separated by semicolons and spaces, so we can use Cookiestring.split ('; ') method to get a separate array of each Cookie (first with var cookiestring = Documents.cookie).

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

Documents.cookie = ' cookiename= ' + Escape (' Cookievalue ')
+ '; expires= ' + expirationdateobj.togmtstring ();

Did you see the dizziness? CookieName represents the name of the cookie, Cookievalue represents the value of the cookie, Expirationdateobj represents the Date object name for which the expiration date is stored, and if no expiration date is required, the second row is not required. Does not specify a expiration date, the browser defaults to expire after the browser is closed (that is, all windows are closed).

First Escape () method: why must use. Because the value of a Cookie requires "only characters that can be used in URL encoding." We know that the "escape ()" method is to encode the string by the URL encoding method, so we only need to use an "escape ()" method to process the value of the output to the cookie, "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 "Documents.cookie = ' cookiename=cookievalue '" as simple as this, but in order to avoid the characters that are not allowed to appear in the URL in Cookievalue, use an escape ().
Then the semicolon before "expires": just notice. Is the semicolon, not the other.
Finally toGMTString () method: Set the time limit of the Cookie is in GMT format, the other format time is not useful.

Now let's do some real 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 24 hours a day
X one hour, 60 minutes, x 60 seconds, 1000 milliseconds a second.
Documents.cookie = ' name=rose;expires= ' + expires.togmtstring ();

Why not use the Escape () method. This is because we know that Rose is a legitimate URL-coded string, which means ' rose ' = Escape (' Rose '). In general, if you set a cookie without escape (), you do not need to unescape () to get the cookie.

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

function GetCookie (cookiename) {
var cookiestring = Documents.cookie;
var start = Cookiestring.indexof (cookiename + ' = ');
The reason to add an equal sign is to avoid the value of some cookies
The same string as CookieName.
if (start = = 1)//not 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 of the methods of the string object, if you don't remember (you're not so forgetful), please check it out quickly. This function all if statements are not brought else, this is because if the condition is set up, the program is running a return statement, in the function hit return, it will terminate the operation, so do not add else also no problem. When the function finds a cookie, it returns the value of the cookie, otherwise it returns "null."

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

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

As you can see, you can delete cookies by simply changing the expiration date to one o'clock (1 milliseconds earlier) and then setting the cookie in the same way.

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.