Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / Javascript
Tip/Trick

JavaScript Cookie Manager

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
30 Oct 2012CPOL2 min read 19.9K   214   5   3
A powerful, stand-alone Javascript cookie manager.

Introduction  

This product was created as a result of the sometimes frustrating experience of dealing with cookies in JavaScript. It aims to provide an API for managing cookies, without relying on admittedly powerful JavaScript frameworks like jQuery or YUI. The product will do the following:

  • Provide a cookie manager that allows developers to set the domain, path, expiration, and security of their cookies on the fly.
  • Check to see if a given cookie exists by name.
  • Provide a list of all cookies and their keys using a simple interface.
  • Read and write cookies and their values.
  • Read and write cookie keys and their values (i.e., multiple-value cookies!)
  • Remove cookies by name.

It is assumed that the person using this code has a general understanding of how cookies work, and is seeking a more robust cookie management solution.

Background

I created this manager as a response to the frustrations I dealt with while trying to manage cookies from client code, specifically the lack of keys (multiple-value cookies). The core read/write of the basic cookie was modeled after the cookie reader/write found here.

I took this and extended it to allow for the use of keys and (hopefully) make it more flexible and powerful for everyday users.

Using the Code

Simply instantiate a new Cookies object and then use the various read/write functions to read and write to your cookies and keys.

JavaScript
//Construct a new, default instance of the Cookies object assume that the current domain 
//is www.mysite.com
var cookieManager = new Cookies();

//Constructs a new instance of the Cookies object specifying the domain, path, expiration date,
//and whether or not to make the cookie "secure."
var cookieManagerWithOptions = new Cookies('mysite.com', '/tools', '10/31/2012', false);    

//Write a new cookie 
cookieManager.write('session_id', 'A10P023Z0');

//Write a key
cookieManager.writeKey('customer', 'name', 'Jeff Smith');
cookieManager.writeKey('customer', 'dob', '07/15/1991');

//Read a cookie  
cookieManager.read('session_id');  //Returns 'A10P023Z0'

//Read a key 
cookieManager.readKey('customer', 'name'); //Returns 'Jeff Smith' 

//Get a collection of objects containing all cookies and their keys
cookieManager.keys();  

// returns [  
// [ session_id, [] ], 
// [customer, [name, dob] ]
// ]

//Check to see if a cookie exists
cookieManager.hasItem('customer'); // returns true
cookieManager.hasItem('dob'); // returns false

//Remove a cookie  
cookieManager.remove('customer');

//Get current domain, path, expiration, and security of the Cookie object
cookieManager.domain(); //returns 'www.mysite.com'
cookieManager.path(); //returns '/'
cookieManager.expires(); //returns ''
cookieManager.secure(); //returns false

//Change manager domain, path, expiration, or security. 
cookieManager.domain('mysite.com');
cookieManager.expires('10/31/2012');
cookieManager.path('/mydir');
cookieManager.secure(true);  

//Please note that each time you want to change the domain or path of a given cookie, 
//you'll have to call the manager's functions to do so, otherwise, it will use the most
//recent value passed into it.  

Points of Interest

This project should work right out of the box and was developed specifically to avoid large libraries like jQuery or YUI. I hope I'm not speaking for too many when I say this, but although I love jQuery and what it can do, I feel like there are many developers (especially young ones) who have a crippling lack of knowledge about JavaScript because of how simple jQuery has made trivial operations.

Sadly, when many of these developers are tasked with doing anything that isn't handled by their chosen library, their first response is always 'let's look for a plugin' and while I agree that code reuse is fantastic, at some point developers need to learn how to think critically and solve problems without relying on oftentimes bulky third party software.

JavaScript is a beautiful and powerful language when wielded properly and, while I don't claim to be a master, a cookie management utility shouldn't be dependent on a gigantic library when a very good solution is a little elbow grease and good old fashioned design work away.

History

  • Version 1.0 - Added sources files, testing harness, and documentation
  • Version 1.1 - Updated source files (testing harness, core) and updated documentation
  • Version 1.2 - Removed a superfluous reference to an unversioned testing harness script, updated core to include ability to fetch path, expiration, and the secure status of the manager
  • Version 1.3 - Addressed bug that was causing failures when attempting to write a key with a blank value

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
William Anderson is a Project Analyst for a moving and logistics company in Fort Smith, AR. He has been working in the development community since 2007, where he primarily focuses on .NET development using C# and VB.NET.

Comments and Discussions

 
QuestionASP NET Pin
Null5111-Mar-13 20:42
Null5111-Mar-13 20:42 
QuestionWill not retrieve cookie in VS2010 Pin
Member 984533618-Feb-13 23:41
Member 984533618-Feb-13 23:41 
AnswerRe: Will not retrieve cookie in VS2010 Pin
William C. Anderson19-Feb-13 5:49
William C. Anderson19-Feb-13 5:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.