Another Cookie Library?
Download
| Download: | sm-cookie.js |
| Version: | |
| Released: |
I can hear it already. "There are already a thousand scripts for getting and setting cookies! Why do we need another one?" That's a good question.
Most of the cookie scripts out there have serious flaws regarding how they search for cookie names. If you're trying to get the value for a cookie named "ant" and there's another cookie named "plant" you could get either value back depending on the order they appear in document.cookie.
ScriptingMagic presents sm-cookie.js. It provides the standard getCookie, setCookie, and deleteCookie functions. It also creates and maintains a window property named cookies which is an associative array for even faster read access.
Example
<script type="text/javascript" src="/javascript/sm-cookie.js" charset="ISO-8859-1"></script>
...
<script type="text/javascript">
...
<script type="text/javascript">
var bat = cookies['bat'];
var at = cookies['at'];
var t = cookies['t'];
document.write('Initial bat value: ' + bat + '<br />');
document.write('Initial at value: ' + at + '<br />');
document.write('Initial t value: ' + t + '<br /><br />');
if (!bat)
{
bat = 1;
at = 100;
t = 'A';
}
else
{
bat++;
at--;
t += String.fromCharCode(bat + 0x40);
}
setCookie('bat', bat);
setCookie('at', at);
setCookie('t', t);
document.write('New bat value: ' + cookies['bat'] + '<br />');
document.write('New at value: ' + cookies['at'] + '<br />');
document.write('New t value: ' + cookies['t'] + '<br />');
</script>
Result
Note
Reload this page to see the cookies change.
Function Signatures
- getCookie(name)
-
- name: the name of the cookie to return
- setCookie(name, value, expiration, path, domain, secure)
-
- name: the name of the cookie
- value: the value to assign to the cookie
- expiration: date the cookie will expire - defaults to session end
- path: path the cookie will be valid for - defaults to current path
- domain: domain the cookie will be valid for - defaults to current domain
- secure: should this cookie only be sent over a secure connection - defaults to false
- deleteCookie(name, path, domain)
-
- name: the name of the cookie
- path: path the cookie will be deleted for - defaults to any path
- domain: domain the cookie will be deleted for - defaults to any domain