|
|
|
The following example is going to show you how easy it is to make cookie. Truly it is easy but only if you have fully documented source code. There are three things you do with a cookie, one, make it, two, read it and three, delete it. Place note this document is not going to tell you how to eat a cookie.
The following example is going to make a cookie hit counter that is for every time the user goes to the web page the counter gets incremented by one. This information is written and read to and from a JavaScript cookie file. This information will be alerted to the user with the alert method. This application will also give the user the opportunity to reset the hit counter which clears the history of the user as if they never came to the web page.
To achieve our goal were going to make three cookie functions and one function utilizer:
The function utilizer is called addHit. This function is made to use the make and read cookie functions it is called every time the document loads. Run Code | View Code
<form>
<input type="button" value="Delete the cookie file" onclick="deleteCookie('counter')">
Make a convenience button to reload the document (This will increase the number of hits by one)
<input type="button" value="Reload" onclick="window.location.reload()">
<form>
<body onload="addHit()">
The addHit function's purpose is to increase the number of times(hits) the user came to this web page by one. This function uses the read cookie and make cookie functions to do it's job.
It declares hits local variable to the value returned by readCookie. readCookie returns the value of a cookie named counter. If the counter cookie was not found readCookie returns null. This function then checks if hits is null if it is not it means the cookie was created before otherwise it wasn't.
If the cookie counter was not created it makes it by calling the makeCookie function. It passes it counter as the name of the cookie and zero (0) as the value since that's going to be the initial value of the counter to be started at and finally 365 for the expiry date which of course is one year at which the cookie will expire.
After make cookie is called a cookie named counter is created and set on the document.cookie property.
If the cookie was created before the parseInt function is used to turn hits in to a numeric value. Once this is done it is possible to increment the value by 1 using the += operator. Finally a cookie with the same name and expiry date is created when calling the makeCookie function but this time the incremented value is passed as the value argument.
function addHit(){
var hits = readCookie("counter")
The cookie does not exist
if(hits == null){
makeCookie("counter",0,365)
Show an alert stating that it's the first time the user has come to this page
alert(This is the first time you have been to this page")
A cookie with the name exists
}else{
makeCookie("counter",hits,365)
Increase hits by one
hits = parseInt(hits) + 1
Show the alert
alert("You have visted this page " + (hits) + " times")
}
}
Read cookie gets the cookie with the specified name out of the available cookies. If the name does not exist null is returned.
The readCookie function must search the value inside document.cookie. If you make a cookie and set it onto document.cookie (with a different name) that new cookie is appended onto the last cookie. Each cookie is delimited by a semi colon and each name/value pair is also delimited by one. This function takes this fact into account for it to get the value for the name out of this difficult to read string.
To understand this function's processes you must understand the substring and indexOf method of a string.
The function first gets the value from document.cookies and inserts into the c variable [var c = document.cookie]. Then it performs a search for given name var [start = c.indexOf(name + "=")], if the name is not found the function returns null and exits.
Otherwise the function tries to get the value for the given name. As the indexOf method returns the index of the name the function can then try and get it's value.
Two things must be achieved to get the value out of the c string:
Well we are already half way through the first step we know the starting position of the name but what we want is the starting point of the name's value. Since the value begins straight after the name it is easy to get the value. All that's done is that the starting position is increased by the length of the name and since there is always an equal sign (=) between the name/value pair the starting point is increased by one more. Ha! We got the starting point of the value for the given name, step one is complete!
start+= name.length+1
it's good that we have the starting position but we need the ending position too. Otherwise if there are other cookies in this cookie and they are pass this cookie they will also be returned as the value.
To get the ending index the semi colon (;) character is searched for, not any semi colon but the first one straight after the starting position of the value. (The starting position was worked out above). A semi colon is searched for because it is known that there is a semi colon delimiter straight after the value. As there are lots of semi colons in a cookie we search for the first one, that is the one after the starting position. If there is no semi colon it means there are no other cookies in this cookie, it also means the end of the cookie file was reached.
var end = c.indexOf(";",start)
If the end of the cookie file was reached (There are no other cookies) All text from the starting position to the end of the cookie file is returned. This means the end position is not needed and not used.
return c.substring(start)
But if the end position was determined (The cookie file has more then one cookie) the value between the starting position and the end position is returned. The end position must be used so all other data pass the end is ignored, since it is not required and is not part of the value.
return c.substring(start,end)
function ReadCookie(name){
var c = document.cookie
Search for the name of the cookie
var start = c.indexOf(name + "=")
No cookie with that name found , terminate this process
if(start == -1) return null
Move the start position to the end of the name and the = sign
start+= name.length+1
Search for the end position starting at start index
var end = c.indexOf(";",start)
end was found
if(end != -1){
v = c.substring(start,end)
No end found
}else{
var v = c.substring(start)
}
Return the value
return v
}
}
The make cookie function makes a cookie according to the cookie specification. The minimum requirements for this function to work are the name and value of the cookie. The Days argument is necessary if the cookie should exist beyond the current session.
This function first checks if the name or value argument is null if it is the function quits because these two arguments are necessary to make a cookie.
Otherwise it sets express to nothing then checks if the days argument was given. If it was it makes an instance of the date object and sets it's time to the current time and adds the current time to the total number of days given (converted to seconds in a day then changed into milliseconds). This gives the expiry date for the cookie. The expiry date is finally converted into the correct string representation for a cookie by using the toUTCString method. Once the expiry date is known it then formats the name/value pair for the expiry date and sets that into the expiry variable.
If path, domain or secure are given their name/value pairs are formatted according to the cookie format. Otherwise they are set to an empty string rather then undefined. This is also true for the date argument. Hence they are all optional.
After the cookie is formatted correctly it is appended to the cookie list contained in cookie property of the document object.
Note as the cookie format states each name/value pair must be delimited with a semi colon.
function makeCookie((name,value,days,path,domain,secure){
if(name == null || value == null){
return
}
By default expires is not set
var expires = ""
If days is not null
if(days){
var date = new Date()
Get todays date
var toDay = date.getTime()
Add todays date to the number of days this cookie should expire
expires = toDay + (days * 24*60*60*1000)
Use the setTime method and pass it expire date
date.setTime(expires)
Get the correct cookie date represenation
expires = date.toUTCString()
format the expire's name/value pair and dimlinter it by a sec";"
expires = ";expires=" + expires
}
format the path's name/value pair
path = (path != null) ? ";path="+path : ";path=/"
format domain's name/value pair
domain = (domain != null) ? ";domain="+domain : ""
format secure' name/value pair
secure = (secure != null) ? ";secure="+secure : ""
append this new cookie to the document.cookie property
document.cookie = name + "=" + value +";" + expires + path + domain + secure
}
The delete cookie function's purpose is to remove the specified cookie from the client's system.
Path and domain are optional. If the domain is provided the cookie will only be deleted if the domain matches the domain in the cookie the same is true for the path argument. The name argument is necessary, it represents the name you used to set the cookie.
Only one line of code is necessary to delete a cookie since the saveCookie's function is called and is passed the same parameters you pass this function. As you may have noticed this function does not need a date parameter that is because the date is the key to delete a cookie. When making a cookie you set the expiry date on it to keep it alive but here we want the cookie to be terminated! To do this the expiry date is set to -1 this will terminate it, since it will cause the date attribute of the cookie to be one day out of date therefore the browser will remove it.
function deleteCookie(name,path,domain){
makeCookie(name,"",-1,path,domain)
}
A cookie is a set, retrieved and deleted by manipulating the cookie's name-valued pair segments.
A name-valued pair contains the name of the cookie and it's value and any other optional arguments that a cookie can have. Each argument is also considered to be a name value pair. After every value a semi colon is added.
The optional arguments are expires, path, domain and secure. The name is the part of the cookie that referredto the value. The value is the part that holds the actual data of the cookie. As you may have guessed name and value are required.
Although Expiry date is an optional parameter if not set on the cookie will die (be deleted) as soon as the web browser is closed). See Expiry date section.
Every document has it's very own document.cookies property.
The cookie format looks like this:
CookieName = cooikeValue [;]
expires = date[;]
path=path[;]
domain=[domain];
secure = [false];
For example:
"xPos= 100;
expires =date;
path=/test;
domain=yahoo.com;
secure = false;"
If there were two cookies set, document.cookie would like:
"xPos= 100; expires =date; path=/test; domain=yahoo.com; secure = false;"
"yPos2=200;expires =date;path=/test;domain=yahoo.com;secure = false;"
If you want to see if a document has cookies attached to it try alert the cookie property like this:
alert(document.cookie)
If the password was to be remembered for a long time it may give a different user time to log into the clients email account and use it at will. Therefore Yahoo.com only remembers the password for about 3 minutes. This makes it more difficult for another user to squeeze through the gaps. Yahoo goes through all this trouble to give the client a better browsing experience. If you want to increase user satisfaction you would do a similar thing.
Yahoo remembers this small amount of information in cookie to make it so the client doesn't have to keep retyping their user name every time they go to the web site. Yahoo cannot use a server side session to do this because it is impossible to know what client is calling therefore how would yahoo show the correct name for the calling client? This is a good time for a cookie do not you think so? It is safe, it is the only way to remember the information, If the cookie gets deleted it doesn't matter because yahoo has the information backed up in a database and it is an extra benefit that will increase user satisfaction. If the user turned off cookies it's only going to make them retype their name at their own expense.
Therefore cookies have a time and place to be utilized.
The information is good to have from the user's point of view because they do not have to keep retyping their username. However If the cookie got deleted, disabled or expired the only thing that will happen is inconvenience for the user (They have to retype their username). This does not effect the rest of the system since the information from the cookie is not necessary since it is backed-up else were.
See size and total cookie limitation in downfalls
To display information without having the user provide any information is the true benefit of a cookie. This allows a web page to automatically customize itself for a specific user as soon as they arrive! A session object on the web server cannot achieve this because there is no way for it to know who and what client is calling. A session must be given information before it can begin tracking the user and any server side scripting language cannot automatically customize a page for a specific user for the same reason but a cookie can!
For example a user visits the same web page twice. The first time they visit they provide the user name and allow the cookie to be saved. The second time and all remaining times they go to the same web page the cookie file can be read and the username can be set into a username text field.
As the saying goes it's best to be safe then sorry therefore do not put any information in a cookie that is sensitive in the first place!
Note: This information is subject to Netscape Navigator web browser.
Wdy, DD-Mon-YYYY HH:MM:SS GMT
where:
wdy - is a string value stating the whole day. eg Monday
DD - is a integer value stating the day of the month. eg: 09
YYYY - is a integer value stating the year. eg: 99
HH - is a integer value stating the hour. eg: 04
MM - is a integer value stating the minute. eg: 02
SS - is a integer value stating the second. eg : 10
for example:
Wednesday, 09-Nov-99 23:12:40 GMT
First you use the getTime method to get the current time.
currentTime = date.getTime()
Now that you have the current time you use the setTime method and give it the current time plus the amount of time the cookie should die. Lets say we want the cookie to be terminated in two days. Therefore you would write:
Date.setTime(currentTime + 24*60*60*1000*2)
As you may have noticed we take the current time and add 24 and then times it by 60 twice. The result will give the total number of seconds in a day. After the total number of seconds is known, it is multiplied by 1000 because we are working milliseconds. Once the total number of milliseconds in a day is calculated it is finally multiplied by 2, 2 meaning two days. If you want the cookie to be terminated in three days just change the 2 to a 3.
The second last step is two convert the date into the format required by a JavaScript cookie. To perform this you simply use toUTCString method. This method returns the corect format for a cookie date.
CookieFormatExpiryDate = date.toUTCString()
Finally you set this expiry date segment along with the other parameters on the cookie property of the document.
|
|||||||||||||||||||||
|
They determine if a client side script can read the cookie. Their function is also to allow or disallow the cookie to be transmitted to the server requesting it.
Path and domain if set determine if the cookie is sent. Domain is checked first. If a match is found then the path is checked. If both path and domain are satisfied the cookie when read is allowed.
Path and domain if set can decrease the amount of network traffic sent to the server because the cookie is not sent if the path and domain do not match. Therefore unnecessary cookies are not sent.
Path and Domain give a server side scripter confidence in that they are getting a cookie they made. If the path and domain match a portion of the URL of the calling document the cookie is sent when requested otherwise is isn't.
For example if a cookie is made with the domain yahoo.com with a path of /email. The cookie will only mach this path and domain if the web browser window is currently located at http://yahoo.com/email
See also: Getting the time | Prompt method