Cookie Handling Routines in JavaScript
These routines are not rocket science, but they do provide a complete set of easy-to-use cookie handling routines in JavaScript. You will find below demonstrations of all the routines, together with the calling sequences used.
The following routines are provided in the zip file:
function sessionCookieTest () {
if (testSessionCookie())
alert ("Session coookies are enabled")
else
alert ("Session coookies are not enabled");
}
function persistentCookieTest () {
if (testPersistentCookie())
alert ("Persistent coookies are enabled")
else
alert ("Persistent coookies are not enabled");
}
function setSessionCookieTest () {
if (testSessionCookie()) {
var myName = document.getElementById('f3CookieName').value;
var myValue = document.getElementById('f3CookieValue').value;
writeSessionCookie (myName, myValue);
alert ("Session cookie written");
}
else
alert ("Sorry - session cookies are currently disabled.");
}
function setPersistentCookieTest () {
if (testPersistentCookie()) {
var myName = document.getElementById('f4CookieName').value;
var myValue = document.getElementById('f4CookieValue').value;
var myPeriod = document.getElementById('f4TimePeriod').value;
var myOffset = document.getElementById('f4TimeValue').value;
writePersistentCookie (myName, myValue, myPeriod, myOffset);
alert ("Persistent cookie written");
}
else
alert ("Sorry - session cookies are currently disabled.");
}
function readCookieTest () {
var myCookieName = document.getElementById('f5CookieName').value;
if (getCookieValue (myCookieName))
alert ('The value of the Cookie is "' + getCookieValue (myCookieName) + '"')
else
alert ("Cookie not found");
}
function deleteCookieTest () {
var myCookieName = document.getElementById('f6CookieName').value;
if (!getCookieValue (myCookieName))
alert ('Cookie does not exist')
else {
deleteCookie (myCookieName);
alert ("Cookie marked for delete");
}
}
Download Zip File (1,360 bytes).
Note: The author is grateful to David Morris for reporting a couple of errors relating to permanent cookies. These were immediately corrected (8 June 2005). The author is also grateful to Peter Pircher who pointed out that the writePersistentCookie function did not work in some browsers owing to differences in the implementation of the JavaScript getFullYear method. This was fixed on 14 June 2007.