JavaScript cookie handling functions - 'Classic' Edition.

These functions are designed to make it easy to store and retrieve a single JavaScript variable or value as a cookie. They use an old-style function-call interface, rather than the object-oriented structure of the newer function set (TIP - use the object versions if you want multi-field cookies and easy multi-cookie handling).

Instant Example:

var Uname = "Jane"
setCookie("UserName", Uname, 365, "/")  // Write 'UserName=Jane' cookie to disk
Uname = getCookie("UserName")
// Read value of "UserName" cookie into variable
deleteCookie("UserName") 
// Delete cookie from disk

Adding the functions to your web pages.
There are two ways to build these functions into your web pages:

Function specifications.

setCookie(Name, Value, Lifespan, Path)
Creates a new cookie, or updates an existing one  

Parameter

Data Type

Meaning

Name

String

Cookie name

Value

String or number

Cookie value

Lifespan (Optional)

Number

Number of days from today to expiry date

Path (Optional)

String

Access path (see 'A quick cookie primer')

Example:

setCookie("UserName", Uname, 365, "/")

This creates a cookie called UserName, with a value equal to the variable Uname, an expiry date 365 days from today, and a path of "/" (so any page from the same domain (website) can access it).

Note that the function generates the expiry date automatically - you just have to specify a lifespan period in days. 

To create a cookie with a specific expiry date, use the setDatedCookie() function instead. This takes a date object for its expiry parameter, instead of period of days. Here's an example:

tdate = new Date(2004, 10, 5)
setDatedCookie("UserName", Uname, tdate, "/")

Apart from the expiry date, setDatedCookie() is identical to setCookie(). 

These functions don't directly support the domain= setting. However you can add one to the path specification, like this:

setCookie("UserName", Uname, 365, "/; domain=mydomain.com")  

 

deleteCookie(Name, Path)
deletes the specified cookie.  

Parameter

Data Type

Meaning

Name

String

Name of cookie to delete

Path (optional)

String

Access path - if you created the cookie using a path of "/", then put "/" as the path for deleteCookie()

Example:

deleteCookie("UserName")

This deletes the cookie called "UserName" by giving it an expiry date of yesterday. It doesn't matter if the cookie doesn't exist - the browser will simply create and delete it in one action.

 

getCookie(Name)
Retrieves the value of  the specified cookie from the page's document.cookie string  

Parameter

Data Type

Meaning

Name

String

Name of cookie to retrieve

Example:

var Uname = getCookie("UserName")

This retrieves the value of the cookie "UserName" from the current page's document.cookie string and places it in the variable "Uname". If no cookie called "UserName" is available, the function returns null (a special JavaScript value which is distinct from "").  

The source!
If you're using Internet Explorer, then you can click here to download the library file to your hard disk (choose 'Save this program to disk' from the pop-up dialog).

Alternatively, here's the source of the classic cookie functions (see top of page for details of copying and pasting them into your pages):

/*

DISCLAIMER: THESE JAVASCRIPT FUNCTIONS ARE SUPPLIED 'AS IS', WITH 
NO WARRANTY EXPRESSED OR IMPLIED. YOU USE THEM AT YOUR OWN RISK. 
NEITHER PAUL STEPHENS NOR PC PLUS MAGAZINE ACCEPTS ANY LIABILITY FOR 
ANY LOSS OR DAMAGE RESULTING FROM THEIR USE, HOWEVER CAUSED. 

Paul Stephens' NetScape-based cookie-handling library

http://web.ukonline.co.uk/paul.stephens/index.htm

TO USE THIS LIBRARY, INSERT ITS CONTENTS IN A <script></script> BLOCK IN THE 
<HEAD> SECTION OF YOUR WEB PAGE SOURCE, BEFORE ANY OTHER JAVASCRIPT ROUTINES.

Feel free to use this code, but please leave this comment block in.

*/

function setCookie (name, value, lifespan, access_path) {
var cookietext = name + "=" + escape(value) 
if (lifespan != null) { 
  var today=new Date() 
  var expiredate = new Date() 
  expiredate.setTime(today.getTime() + 1000*60*60*24*lifespan)
  cookietext += "; expires=" + expiredate.toGMTString()
}
if (access_path != null) { 
  cookietext += "; PATH="+access_path 
}
document.cookie = cookietext 
return null 
}


function setDatedCookie(name, value, expire, access_path) {
var cookietext = name + "=" + escape(value) 
   + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
if (access_path != null) { 
  cookietext += "; PATH="+access_path 
}
document.cookie = cookietext 
return null 
}


function getCookie(Name) {
var search = Name + "=" 
var CookieString = document.cookie 
var result = null 
if (CookieString.length > 0) { 
    offset = CookieString.indexOf(search) 
    if (offset != -1) { 
        offset += search.length 
        end = CookieString.indexOf(";", offset) 
        if (end == -1) {
           end = CookieString.length }
        result = unescape(CookieString.substring(offset, end)) 
  
}
return result 
}


function deleteCookie(Name, Path) {
setCookie(Name,"Deleted", -1, Path)
}

/* END OF FUNCTIONS */