Anda di halaman 1dari 15

You really don't need much knowledge to use this script, it's pretty much plug and play,

but we'll explain it's main part and how to use them anyway. If you have specific questions, please post them in our Javascript Forum and we will answer them there.
Set Cookie Javascript Function

You need to put the name and values in quotes when you call the function, like this: Set_Cookie( 'mycookie', 'visited 9 times', 30, '/', '', '' );. Don't forget to put in empty quotes for the unused parameters or you'll get an error when you run the code. This makes the cookie named 'mycookie', with the value of 'visited 9 times', and with a life of 30 days, and the cookie is set to your root folder. The Set_Cookie values for 'domain' and 'secure' are not utilized. Use 'domain' on the Javascript cookie if you are using it on a subdomain, like widgets.yoursite.com, where the cookie is set on the widgets subdomain, but you need it to be accessible over the whole yoursite.com domain. It's good practice to not assume the path to the site root will be set the way you want it by default, so do this manually as a rule, '/'. If no value is set for expires, it will only last as long as the current session of the visitor, and will be automatically deleted when they close their browser.
function Set_Cookie( name, value, expires, path, domain, secure ) { // set time, it's in milliseconds var today = new Date(); today.setTime( today.getTime() ); /* if the expires variable is set, make the correct expires time, the current script below will set it for x number of days, to make it for hours, delete * 24, for minutes, delete * 60 * 24 */ if ( expires ) { expires = expires * 1000 * 60 * 60 * 24; } var expires_date = new Date( today.getTime() + (expires) ); document.cookie = name + "=" +escape( value ) + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + ( ( path ) ? ";path=" + path : "" ) + ( ( domain ) ? ";domain=" + domain : "" ) + ( ( secure ) ? ";secure" : "" ); }

This will set the cookie. It's the most complicated part, but actually for most purposes all you need to set are the first 4 parameters, name, value, expires, and path. If you want the cookie available only in one folder, you will need to add '/folder_name/' as a path variable, that tells the script to set the cookie for the just that path, not for the whole domain.

As a good general rule, set the path to '/', the root of your website. Generally 'domain' and 'secure' are not something you will be needing to use unless you set the cookie on a subdomain, in which case you may want to set the domain to your primary domain if you want it to be accessible from the main domain, or other subdomains.
Get Cookie Javascript Function

// this fixes an issue with the old method, ambiguous values // with this test document.cookie.indexOf( name + "=" ); function Get_Cookie( check_name ) { // first we'll split this cookie up into name/value pairs // note: document.cookie only returns name=value, not the other components var a_all_cookies = document.cookie.split( ';' ); var a_temp_cookie = ''; var cookie_name = ''; var cookie_value = ''; var b_cookie_found = false; // set boolean t/f default f for ( i = 0; i < a_all_cookies.length; i++ ) { // now we'll split apart each name=value pair a_temp_cookie = a_all_cookies[i].split( '=' ); // and trim left/right whitespace while we're at it cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, ''); // if the extracted name matches passed check_name if ( cookie_name == check_name ) { b_cookie_found = true; // we need to handle case where cookie has no value but exists (no = sign, that is): if ( a_temp_cookie.length > 1 ) { cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') ); } // note that in cases where cookie is initialized but no value, null is returned return cookie_value; break; } a_temp_cookie = null; cookie_name = ''; } if ( !b_cookie_found ) { return null; } }

Please note that the above version fixes some fairly serious issues with the old version, here listed below for comparison. The original utterly fails to handle cases where cookie names are substrings of other cookies, say like: site_main, site_main2 and so on. Thanks to ThoughtfulCoder for point this problem out. What's amazing to contemplate that this original code has been up for years without anyone noticing that weakness.
// this function gets the cookie, if it exists // don't use this, it's weak and does not handle some cases // correctly, this is just to maintain legacy information function Get_Cookie( name ) { var start = document.cookie.indexOf( name + "=" ); var len = start + name.length + 1; if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) { return null; } if ( start == -1 ) return null; var end = document.cookie.indexOf( ";", len ); if ( end == -1 ) end = document.cookie.length; return unescape( document.cookie.substring( len, end ) ); }

This will retrieve the cookie by name, if the cookie does not exist, it will return false, so you can do things like if ( Get_Cookie( 'your_cookie' ) ) do something.
Delete Cookie Javascript Function

// this deletes the cookie when called function Delete_Cookie( name, path, domain ) { if ( Get_Cookie( name ) ) document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT"; }

Here all you need to do is put in: Delete_Cookie('cookie name', '/', '') and the cookie will be deleted. Remember to match the cookie name, path, and domain to what you have it in Set_Cookie exactly, or you may get some very hard to diagnose errors. WARNING: Do not assume the Cookie has actually been deleted during that session, both Opera and IE have in some of their browser versions maintained the cookie until you restart your browser even if you have deleted it in the script. If script functionality depends on the delete action having happened, make sure you do another Get_Cookie test on the deleted cookie to make sure it's actually deleted.
Sample Page Code for Javascript Cookies

<script type="text/javascript">

// remember, these are the possible parameters for Set_Cookie: // name, value, expires, path, domain, secure Set_Cookie( 'test', 'it works', '', '/', '', '' ); if ( Get_Cookie( 'test' ) ) alert( Get_Cookie('test')); // and these are the parameters for Delete_Cookie: // name, path, domain // make sure you use the same parameters in Set and Delete Cookie. Delete_Cookie('test', '/', ''); ( Get_Cookie( 'test' ) ) ? alert( Get_Cookie('test')) : alert( 'it is gone'); </script>

If you run this, what will happen is that you will get two alerts, the first one will have the content you set with Set_Cookie, the second will say 'it is gone' since you have now deleted the cookie. That's about it.
Manual Downloads

If for some reason the above download links didn't work, you can download these here:

First an introduction to cookies, and a summary of document.cookie, followed by an example. Then come the three functions and their explanation.
Cookies

Cookies were originally invented by Netscape to give 'memory' to web servers and browsers. The HTTP protocol, which arranges for the transfer of web pages to your browser and browser requests for pages to servers, is state-less, which means that once the server has sent a page to a browser requesting it, it doesn't remember a thing about it. So if you come to the same web page a second, third, hundredth or millionth time, the server once again considers it the very first time you ever came there. This can be annoying in a number of ways. The server cannot remember if you identified yourself when you want to access protected pages, it cannot remember your user preferences, it cannot remember anything. As soon as personalization was invented, this became a major problem. Cookies were invented to solve this problem. There are other ways to solve it, but cookies are easy to maintain and very versatile.
How cookies work

A cookie is nothing but a small text file that's stored in your browser. It contains some data:
1. A name-value pair containing the actual data 2. An expiry date after which it is no longer valid 3. The domain and path of the server it should be sent to

As soon as you request a page from a server to which a cookie should be sent, the cookie is added to the HTTP header. Server side programs can then read out the information and decide that you have the right to view the page you requested or that you want your links to be yellow on a green background. So every time you visit the site the cookie comes from, information about you is available. This is very nice sometimes, at other times it may somewhat endanger your privacy. Fortunately more and more browsers give you the opportunity to manage your cookies (deleting the one from the big ad site, for example). Cookies can be read by JavaScript too. They're mostly used for storing user preferences.
name-value

Each cookie has a name-value pair that contains the actual information. The name of the cookie is for your benefit, you will search for this name when reading out the cookie information.

If you want to read out the cookie you search for the name and see what value is attached to it. Read out this value. Of course you yourself have to decide which value(s) the cookie can have and to write the scripts to deal with these value(s).
Expiry date

Each cookie has an expiry date after which it is trashed. If you don't specify the expiry date the cookie is trashed when you close the browser. This expiry date should be in UTC (Greenwich) time.
Domain and path

Each cookie also has a domain and a path. The domain tells the browser to which domain the cookie should be sent. If you don't specify it, it becomes the domain of the page that sets the cookie, in the case of this page www.quirksmode.org. Please note that the purpose of the domain is to allow cookies to cross sub-domains. My cookie will not be read by search.quirksmode.org because its domain is www.quirksmode.org . When I set the domain to quirksmode.org, the search sub-domain may also read the cookie. I cannot set the cookie domain to a domain I'm not in, I cannot make the domain www.microsoft.com . Only quirksmode.org is allowed, in this case. The path gives you the chance to specify a directory where the cookie is active. So if you want the cookie to be only sent to pages in the directory cgi-bin, set the path to /cgi-bin. Usually the path is set to /, which means the cookie is valid throughout the entire domain. This script does so, so the cookies you can set on this page will be sent to any page in the www.quirksmode.org domain (though only this page has a script that searches for the cookies and does something with them).
document.cookie

Cookies can be created, read and erased by JavaScript. They are accessible through the property document.cookie. Though you can treat document.cookie as if it's a string, it isn't really, and you have only access to the name-value pairs. If I want to set a cookie for this domain with a name-value pair 'ppkcookie1=testcookie' that expires in seven days from the moment I write this sentence, I do
document.cookie = 'ppkcookie1=testcookie; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'

1. 2. 3. 4. 5.

First the name-value pair ('ppkcookie1=testcookie') then a semicolon and a space then the expiry date in the correct format ('expires=Thu, 2 Aug 2001 20:47:11 UTC') again a semicolon and a space then the path (path=/)

This is a very strict syntax, don't change it! (Of course the script manages these dirty bits for you) Also, even though it looks like I'm writing this whole string to the string document.cookie, as soon as I read it out again I only see the name-value pair:
ppkcookie1=testcookie

If I want to set another cookie, I again do


document.cookie = 'ppkcookie2=another test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'

The first cookie is not overwritten, as it would when document.cookie would be a real string. Instead the second one is added to document.cookie, so if we read it out we get
ppkcookie1=testcookie; ppkcookie2=another test

If I reset a cookie
document.cookie = 'ppkcookie2=yet another test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'

the old cookie is overwritten and document.cookie reads


ppkcookie1=testcookie; ppkcookie2=yet another test

To read out a cookie you have to treat document.cookie as a string and search for certain characters (semicolons, for instance) and for the cookie name. I'll explain how to do it below. Finally, to remove a cookie, set it with an expiry date before today. The browser sees that the cookie has expired and removes it.
document.cookie = 'ppkcookie2=yet another test; expires=Fri, 27 Jul 2001 02:47:11 UTC; path=/'

Example

If you're thoroughly confused by all this strange syntax, try the example below. You can set two cookies, ppkcookie1 and ppkcookie2. Fill in the desired value in the text box. The value of the cookie should be Create cookie 1 Read cookie 1 Erase cookie 1.

Create cookie 2 Read cookie 2 Erase cookie 2. For comparision, read out document.cookie. I set the cookies to remain active for seven days. If you return to this page within that time, you'll get an alert that the cookie(s) is/are still active. Try it by setting a cookie, then reloading this page.
The scripts

These are the three scripts you need.


function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); }

Explanation

The functions are not very difficult, the hardest part is creating the correct syntax for setting a cookie.
createCookie

When calling createCookie() you have to give it three bits of information: the name and value of the cookie and the number of days it is to remain active. In this case the name-value pair should become ppkcookie=testcookie and it should be active for 7 days.
createCookie('ppkcookie','testcookie',7)

If you set the number of days to 0 the cookie is trashed when the user closes the browser. If you set the days to a negative number the cookie is trashed immediately. The function receives the arguments and starts doing its job.
function createCookie(name,value,days) {

First of all see if there is a days value. If there isn't we don't need to do the time calculation.
if (days) {

If there is, create a new Date object containing the current date.
var date = new Date();

Now get the current Time (in milliseconds) and add the required number of days (in milliseconds). Set the Time of the date to this new value, so that it now contains the date in milliseconds that the cookie should expire.
date.setTime(date.getTime()+(days*24*60*60*1000));

Set the variable expires to this date in the UTC/GMT format required by cookies.
var expires = "; expires="+date.toGMTString(); }

If 0 is passed to the function, expires is not set and the cookie expires when the user closes his browser..
else var expires = "";

Finally write the new cookie into document.cookie in the correct syntax.
document.cookie = name+"="+value+expires+"; path=/"; }

Cookie created.
readCookie

To read out a cookie, call this function and pass the name of the cookie. Put the name in a variable. First check if this variable has a value (if the cookie does not exist the variable becomes null, which might upset the rest of your function), then do whatever is necessary.
var x = readCookie('ppkcookie1') if (x) { [do something with x] }

The function receives the argument and starts.


function readCookie(name) {

We're going to search for the name of the cookie, followed by an =. So create this new string and put it in nameEQ:
var nameEQ = name + "=";

Then split document.cookie on semicolons. ca becomes an array containing all cookies that are set for this domain and path.
var ca = document.cookie.split(';');

Then we go through the array (so through all cookies):


for(var i=0;i < ca.length;i++) {

Set c to the cookie to be checked.


var c = ca[i];

If the first character is a space, remove it by using the substring() method. Continue doing this until the first character is not a space.
while (c.charAt(0)==' ') c = c.substring(1,c.length);

Now string c begins with the name of the current cookie. If this is the name of the desired cookie
if (c.indexOf(nameEQ) == 0)

we've found what we were looking for. We now only need to return the value of the cookie, which is the part of c that comes after nameEQ. By returning this value we also end the function: mission accomplished.
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); }

If, after having gone through all cookies, we haven't found the name we're looking for, the cookie is not present. We return null.
return null; }

Cookie read.

eraseCookie

Erasing is extremely simple.


eraseCookie('ppkcookie')

Pass the name of the cookie to be erased


function eraseCookie(name) {

and call createCookie() to set the cookie with an expiry date of one day ago.
createCookie(name,"",-1); }

The browser, seeing that the expiry date has passed, immediately removes the cookie.

Reading cookies works significantly differently from writing cookies. While we can write each cookie separately simply by setting document.cookie to the values we want the new (or replacement) cookie to have, JavaScript does not provide a way to access the cookies separately when reading them but instead if you try to read the value back from document.cookie you get all of the cookies passed to the current page as one long string. So in order to actually access the individual cookies that are passed to the web page we need to write our own code that will split up the content of document.cookie into the individual cookies. The simplest way to do this is to create a cookie object where each individual cookie exists as a property of the cookie object. The function in this example code does exactly that while the last line of the example code shows how we can test if a cookie with the name 'user' exists and if so then assign the value to a field of that name.

var cookie, user; allCookies = function() { var cr, ck, cv; cr = []; if (document.cookie != '') { ck = document.cookie.split('; '); for (var i=ck.length - 1; i>= 0; i--) { cv = ck.split('='); cr[ck[0]]=ck[1]; } } return cr; }; cookie = allCookies(); if (cookie.user != null) user = cookie.user;

Actually updating a cookie is slightly different from just replacing a cookie in that the new value we want to place in the cookie is dependent in some way on whether the cookie already exists and if so on what it contains. This means that we need to read the existing cookie before we can write a replacement for it. One thing to note is that when we read a cookie we have no way of telling when the existing cookie is due to expire or whether the cookie is restricted to a specific folder or available across the entire domain. You need to set a new retention period when you replace the cookie and need to keep track of what scope you want the cookie to have within your pages so as to apply the same domain or path option each time. The only thing that you are actually able to read when updating rather than just replacing a cookie is the actual value of the data stored in the cookie.

In this example we are going to use a cookie named 'accesscount' to count the number of times that our visitor has accessed our page where no more than seven days has elapsed between visits. Should more than seven days elapse between visits then the cookie will expire and the next visit will restart counting from zero. We are using the allCookies() and writeCookie() functions from the prior examples so the only piece of new code we need in order to actually do the update is in the last two lines.

var cookie; allCookies = function() { var cr, ck, cv; cr = []; if (document.cookie != '') { ck = document.cookie.split('; '); for (var i=ck.length - 1; i>= 0; i--) { cv = ck.split('='); cr[ck[0]]=ck[1]; } } return cr; }; writeCookie = function(cname, cvalue, days,opt) { var dt, expires, option; if (days) { dt = new Date(); dt.setTime(dt.getTime()+(days*24*60*60*1000)); expires = "; expires="+dt.toGMTString(); } else expires = ''; if (opt) { if ('/' = substr(opt,0,1)) option = "; path="+opt; else option = "; domain="+opt; } else option = ''; document.cookie = cname+"="+cvalue+expires+option; } cookie = allCookies(); if (cookie.accesscount != null) writeCookie('mycookie', cookie.accesscount + 1,7); else writeCookie('mycookie', 1,7);

Get Cookie value and set cookie value

import import import import

org.apache.commons.httpclient.Cookie; org.apache.commons.httpclient.HttpState; org.apache.commons.httpclient.HttpClient; org.apache.commons.httpclient.methods.GetMethod;

public class GetCookiePrintAndSetValue { public static void main(String args[]) throws Exception { HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "My Browser"); GetMethod method = new GetMethod("http://localhost:8080/"); try{ client.executeMethod(method); Cookie[] cookies = client.getState().getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; System.err.println( "Cookie: " + cookie.getName() + ", Value: " + cookie.getValue() + ", IsPersistent?: " + cookie.isPersistent() + ", Expiry Date: " + cookie.getExpiryDate() + ", Comment: " + cookie.getComment()); cookie.setValue("My own value"); } client.executeMethod(method); } catch(Exception e) { System.err.println(e); } finally { method.releaseConnection(); } } }

<script type="text/javascript"> <!-expireDate=new Date("dec 25,2005 00:00:00"); function test1(){ cookievalues="Hello World" document.cookie = "mycookie="+escape(cookievalues)+";path=/;expires=" + expireDate } function test2(){ cookievalues="New Cookie Value" document.cookie = "mycookie="+escape(cookievalues)+";path=/;expires=" + expireDate } function test3(){ cookievalues="Help me, I'm melting" document.cookie = "mycookie="+escape(cookievalues)+";path=/" }

// --> </script> <a href="#null" onclick="test1()">Update Cookie 1</a> <a href="#null" onclick="test2()">Update Cookie 2</a> <a href="#null" onclick="test3()">Update Cookie 3</a>When you click Update Cookie 3 the persistant cookie is deleted

Anda mungkin juga menyukai