A cookie is often used to identify a user.
A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.Cookies are a plain text data record of 5 variable-length fields:
- Expires: The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
- Domain: The domain name of your site.
- Path: The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
- Secure: If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
- Name=Value: Cookies are set and retrieved in the form of key-value pairs.
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this.
document.cookie = "key1=value1;key2=value2;expires=date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.Note: Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value.
Example
Try the following. It sets a customer name in an input cookie.
<html>
<head>
<script type="text/javascript">
<!--function WriteCookie()
{
if( document.myform.customer.value == "" ){
alert ("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>
Output
Enter name:
Now your machine has a cookie called name. You can set multiple cookies using multiple key=value pairs separated by comma.
Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value.You can use strings' split() function to break a string into key and values as follows:
Example
Try the following example to get all the cookies.
<html>
<head>
<script type="text/javascript">
<!--function ReadCookie()
{
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
Note: Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time, please try to digest it.
Output
click the following button and see the result:
Note: There may be some other cookies already set on your machine. The above code will display all the cookies set on your machine.
Get Cookie
Setting Cookies Expir y DateYou can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the ‘expires’ attribute to a date and time.
Example
Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.
<html>
<head>
<script type="text/javascript">
<!--function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
Output
Enter Cookie Name:
Deleting a Cookie
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiry date to a time in the past.
Example
Try the following example. It illustrates how to delete a cookie by setting its expiry date to one month behind the current date.
<html>
<head>
<script type="text/javascript">
<!--function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
Examples of cookies:
- Name cookie - The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like "Welcome John Doe!" The name is retrieved from the stored cookie
- Password cookie - The first time a visitor arrives to your web page, he or she must fill in a password. The password is then stored in a cookie. Next time the visitor arrives at your page, the password is retrieved from the cookie
- Date cookie - The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday August 11, 2005!" The date is retrieved from the stored cookie
Create and Store a Cookie
In this example we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web page, he or she will be asked to fill in her/his name. The name is then stored in a cookie. The next time the visitor arrives at the same page, he or she will get welcome message.First, we create a function that stores the name of the visitor in a cookie variable:
function setCookie(c_name,value,expiredays)
{ var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toUTCString()); } |
In the function above we first convert the number of days to a valid date, then we add the number of days until the cookie should expire. After that we store the cookie name, cookie value and the expiration date in the document.cookie object.
Then, we create another function that checks if the cookie has been set:
function getCookie(c_name)
{ if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start,c_end)); } } return ""; } |
Last, we create the function that displays a welcome message if the cookie is set, and if the cookie is not set it will display a prompt box, asking for the name of the user:
function checkCookie()
{ username=getCookie('username'); if (username!=null && username!="") { alert('Welcome again '+username+'!'); } else { username=prompt('Please enter your name:',""); if (username!=null && username!="") { setCookie('username',username,365); } } } |
<html>
<head>
<script type="text/javascript">
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
function checkCookie()
{
username=getCookie('username');
if (username!=null && username!="")
{
alert('Welcome again '+username+'!');
}
else
{
username=prompt('Please enter your name:',"");
if (username!=null && username!="")
{
setCookie('username',username,365);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
No comments:
Post a Comment
Please write your view and suggestion....