JavaScripts :: Cookies :: Get, Set and Print Cookies
This javascript will set cookies, delete cookies, read cookies, print cookies and get cookies. It's a definitive 'How to' guide on cookies. Subsequent actions can then be executed depending on whether or not a particular cookie exists.
The Script
Copy and paste the following script anywhere within your web page.
<script type="text/javascript">
<!--
/* Copyright http://www.perlscriptsjavascripts.com
Free and commercial Perl and JavaScripts */
function getCookie(w){
cName = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split('; ');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0] == w){
cName = unescape(NmeVal[1]);
}
}
return cName;
}
function printCookies(w){
cStr = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split('; ');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0]){
cStr += NmeVal[0] + '=' + unescape(NmeVal[1]) + '; ';
}
}
return cStr;
}
function setCookie(name, value, expires, path, domain, secure){
cookieStr = name + "=" + escape(value) + "; ";
if(expires){
expires = setExpiration(expires);
cookieStr += "expires=" + expires + "; ";
}
if(path){
cookieStr += "path=" + path + "; ";
}
if(domain){
cookieStr += "domain=" + domain + "; ";
}
if(secure){
cookieStr += "secure; ";
}
document.cookie = cookieStr;
}
function setExpiration(cookieLife){
var today = new Date();
var expr = new Date(today.getTime() + cookieLife * 24 * 60 * 60 * 1000);
return expr.toGMTString();
}
// -->
</script>
Examples for calling the cookie functions
Use any of the following JavaScript examples to get cookies, set cookies, print all cookies or delete cookies.
<script type="text/javascript">
<!--
// set a session cookie which will expire when the browser is closed
setCookie('hasVisited', 'Yes');
// get the value of a cookie already set
cookieValue = getCookie('hasVisited');
alert(cookieValue) // Yes
// set a cookie which will expire in 1 day
setCookie('hasVisitedToday', 'Yes', 3);
// set a cookie which will expire in 3 days and be accessible site wide
setCookie('hasVisitedSite', 'Yes', 3, '/');
// set a cookie which will expire in 3 days and be accessible only while
// in the 'members' folder
setCookie('cookieName', 'cookieValue', 3, '/members');
// set a cookie which will expire in 3 days and be accessible only while
// in the 'members' folder, and will be transmitted securely
setCookie('cookieName', 'cookieValue', 3, '/members', '', 1);
// set a cookie which will expire in 3 days and be accessible site wide
// and set the domain name
setCookie('cookieName', 'cookieValue', 3, '/', 'perlscriptsjavascript.com');
// print all cookies set for the domain
allCookies = printCookies();
document.write(allCookies);
alert(allCookies);
// delete a specific cookie by setting it's expiration date to the past
// and defining a blank value
setCookie('cookieName', '', -1);
// see notes on deleting cookies below if your cookies are not being deleted
// -->
</script>
A few notes on setting cookies
Cookies with out an expiration date are known as session cookies. Session cookies expire the moment a browser is closed, or they can be deleted before the browser is closed. When settings cookies, it pays to remember or keep a note on the parameters set, because if you need to delete a cookie, you must use the exact same parameters. For example, if you set the path for a cookie when you created it, but you don't set the same path while trying to delete it, it will not be deleted.
A note on secure cookies
Secure cookies are transmitted securely when set as such. To set a secure cookie with the above functions, set the secure argument to either 1 or true. If using secure cookies, make sure you also read the notes below on setting the domain.
A note on setting the path
When setting the path for cookies, using '/' is a synonym for the entire website. If the path is left blank, the cookie is set for the directory the user is currently in. For example, if a cookie is set on this website with a path of '/members' then that cookie is only available while the user in visiting a page in the http://www.perlscriptsjavascripts.com/members directory.
A note on setting the domain
Setting the domain parameter is always good idea, but especially so when on a secure website. Let's say a visitor came to our site by typing 'http://perlscriptsjavascripts.com/' into their browser's address bar. If we don't set the domain, the domain is automatically set by the browser to 'http://perlscriptsjavascripts.com'. But most of the links that point to our website use the 'www' sub-domain, as in 'http://www.perlscriptsjavascripts.com/'. A little known fact is that 'www' is actually a sub-domain of the top level domain, which in this case is 'http://perlscriptsjavascripts.com'. So the next time the same visitor comes along by clicking a link which points to http://www.perlscriptsjavascripts.com/ the cookie will not be available.
The same is true for secure URLs, as in 'https://perlscriptsjavascripts.com'. This cookie will not be available when visiting 'http://perlscriptsjavascripts.com'. This is a very common mistake made by developers and often the cause of great frustration.
A simple solution which covers all possibilities is to set the domain to the top level domain with a . (period) prefixed. As in '.perlscriptsjavascripts.com'. The following cookie will be available no matter where the user is on our website :
setCookie('cookieName', 'cookieValue', 3, '/', '.perlscriptsjavascripts.com', 1);
A note on setting the expiration date and time
To set a cookie's expiration to hours rather than days, remove the * 24 from the setExpiration function. If the expires argument is left blank, the cookie will expire when the browser's session expires (when the browser is closed).
A note on deleting cookies
Attempting to delete cookies can also be a source of great frustration. To delete a cookie, you must overwrite the cookie with a negative date and time and set it's value to null. In most browsers, the cookie actually still exists until the browser is closed. By setting a blank value, the cookie's content is immediately no longer available. What's more, when overwriting cookies you must use the exact same parameters used when you set it. For example :
// set a new cookie
setCookie('cookieName', 'cookieValue', 3, '/', '.perlscriptsjavascripts.com');
// delete the same cookie, by setting a negative date
setCookie('cookieName', '', -1, '/', '.perlscriptsjavascripts.com');
// this will NOT delete the cookie, because the path differs
setCookie('cookieName', '', -1, '', '.perlscriptsjavascripts.com');
|