Skip to content

Instantly share code, notes, and snippets.

@maxcal
Created August 3, 2012 12:43
Show Gist options
  • Select an option

  • Save maxcal/3247339 to your computer and use it in GitHub Desktop.

Select an option

Save maxcal/3247339 to your computer and use it in GitHub Desktop.
CookieObject
/*
* Simple implemtation of storing objects in a cookie.
*
* Requires native JSON support or
* https://github.com/douglascrockford/JSON-js/blob/master/json2.js
* for cross browser JSON support.
*
* @param string key - [req] the key of the cookie to create or read.
* @param object data - [opt] the object to store
* @param int days - [opt] How many days before cookie expires
* @param string path - [opt] the path of the cookie
*
* @author max.calabrese@nordinteractive.se
*
* @example
// Read a cookie
var cookie = new CookieObject('foo');
// create a Cookie
var cookie = new CookieObject('foo', {a : 'b'});
cookie.data.a
// b
*
*/
function CookieObject(key, data, days, path) {
// Creates a new cookie.
this.data = data;
this.key = key;
this.days = days || 30;
this.path = path;
function serialize(obj) {
return JSON.stringify(obj);
}
function deserialize(str) {
return JSON.parse(str);
}
this.read = function () {
var nameEQ = this.key + "=",
ca = document.cookie.split(';'),
i, c;
for (i = 0; i < ca.length; i++) {
c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return deserialize(c.substring(nameEQ.length, c.length));
}
}
return null;
}
this.write = function(key, value, days, path) {
var expires, date, path_to, new_cookie;
path_to = "path=/";
if (days) {
date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
if (path){
path_to = path_to + path;
}
document.cookie = key + "=" + value + expires + ";"+ path_to;
new_cookie = this.read(key);
return new_cookie;
}
if (!data) {
this.data = this.read();
}
else {
this.write(this.key, serialize(this.data), this.days, this.path );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment