JavaScript Cookies Functions

I wrote and gathered a set of JavaScript functions to manipulate cookies. You can download the source file as cookies.js. The remainder of the document tests the functions (in your browser) and shows how the functions are used. Also see the top of the JavaScript source file for a quick synopsis. Finally, visit http://www.kubat.nl/pages/blogaria/199#199 for a description.

Initializing

The code is contained in a file cookies.js which must be sourced:
<html>
  <head>
    <title>JavaScript Cookie Functions Test</title>
    <script type="text/javascript" src="cookies.js"></script>
  </head>
  <body> <!-- Body goes here --> </body>
</html>  
    

Setting Cookies

For example: This sets cookies named test0 through test9 having values value_of_test_0 and so on.
for (var i = 0; i < 10; i++)
    cookie_set('test' + i, 'value_of_test_' + i, 1, '/');
		    

Getting the value of a given cookie

This returns the value of a given cookie, e.g. test4:
document.write('The value of cookie test4 is: ' +
               cookie_get('test4'));
    

Listing all cookies

Function cookie_names() returns an array of the names of all cookies:
document.write('<ul>'); 
var cookies = cookie_names();
for (var i = 0; i < cookies.length; i++)
    document.write('<li>Cookie <i>' + cookies[i] + '</i>' +
	           ' has value ' + cookie_get(cookies[i]));
document.write('</ul>');
    

Deleting one cookie

Function cookie_delete() removes a given cookie. It is exactly the same as calling cookie_set() with value '' (empty string). For example, this kills cookie test1:
cookie_delete('test1');      
document.write('<ul>'); 
var cookies = cookie_names();
for (var i = 0; i < cookies.length; i++)
    document.write('<li>Cookie <i>' + cookies[i] + '</i>' +
	           ' has value ' + cookie_get(cookies[i]));
document.write('</ul>');
    

Deleting a number of cookies

Function cookies_delete() (mind the s) deletes a "blacklist" of cookies. E.g., the following kills cookies test7 and test9:
cookies_delete(new Array('test7', 'test9')); 
document.write('<ul>'); 
var cookies = cookie_names();
for (var i = 0; i < cookies.length; i++)
    document.write('<li>Cookie <i>' + cookies[i] + '</i>' +
	           ' has value ' + cookie_get(cookies[i]));
document.write('</ul>');
    

Deleting all cookies but a few

Function cookies_delete_except() (mind the s) deletes cookies except when they are in a "whitelist". E.g., the following kills all cookies but test5 and test6:
cookies_delete_except(new Array('test5', 'test6'));  
document.write('<ul>'); 
var cookies = cookie_names();
for (var i = 0; i < cookies.length; i++)
    document.write('<li>Cookie <i>' + cookies[i] + '</i>' +
	           ' has value ' + cookie_get(cookies[i]));
document.write('</ul>');