Entry
How can I read and write cookies with client side Javascript?
How can I delete a cookie?
Nov 21st, 2001 05:59
Thor Larholm, Martin Honnen, http://tech.irt.org/articles/js064/index.htm
Basically you just set
document.cookie = 'cookieName=cookieValue'
to set a cookie and then parse
document.cookie
to read a cookie.
The following functions setCookie and getCookie do the work of setting
and getting a cookie properly; setCookie takes at least two arguments,
the cookie name and the cookie value, and 4 optional arguments the
first being an expires Date object, the second be a string path, the
third being a string domain, and the last being a boolean value secure
(for HTTPS cookies only):
function setCookie (cookieName, cookieValue, expires, path, domain,
secure) {
document.cookie =
escape(cookieName) + '=' + escape(cookieValue)
+ (expires ? '; EXPIRES=' + expires.toGMTString() : '')
+ (path ? '; PATH=' + path : '')
+ (domain ? '; DOMAIN=' + domain : '')
+ (secure ? '; SECURE' : '');
}
function getCookie (cookieName) {
var cookieValue = null;
var posName = document.cookie.indexOf(escape(cookieName) + '=');
if (posName != -1) {
var posValue = posName + (escape(cookieName) + '=').length;
var endPos = document.cookie.indexOf(';', posValue);
if (endPos != -1)
cookieValue = unescape(document.cookie.substring(posValue,
endPos));
else
cookieValue = unescape(document.cookie.substring(posValue));
}
return cookieValue;
}
Examples of use:
// set a session cookie which expires after the browser is closed
setCookie ('cookieName', 'cookieValue');
// set a cookie which expires after 24 hours
var now = new Date();
var tomorrow = new Date(now.getTime() + 1000 * 60 * 60 * 24)
setCookie ('cookieName', 'cookieValue', tomorrow);
// set a cookie with a path
setCookie ('cookieName', 'cookieValue', null, '/')
To delete a cookie you just set it with an expires date in the past:
var now = new Date();
var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
setCookie('cookieName', 'cookieValue', yesterday);