Wednesday, November 21, 2007

Cookies Anyone?

Looking back in my code I found an object that may be useful for some of you out there. This object is made to work with Cookies (and a cofee cup too! -stupid joke I know).

We all know (Javascript programmers) how easy is to work with Cookies and for most of you this object is nothing spectacular to develop but if it saves programming time for you I have reach my goal.

No more talking, here's the code:


var Cookie = {
set: function(name, value, daysToExpire) {
var expire = '';
if (daysToExpire != undefined) {
var d = new Date();
d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
expire = '; expires=' + d.toGMTString();
}
return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
},
get: function(name) {
var cookie = document.cookie.match(new RegExp('(^|;)\s*' + escape(name) + '=([^;\s]*)'));
return (cookie ? unescape(cookie[2]) : null);
},
erase: function(name) {
var cookie = Cookie.get(name) || true;
Cookie.set(name, '', -1);
return cookie;
},
accept: function() {
if (typeof navigator.cookieEnabled == 'boolean') {
return navigator.cookieEnabled;
}
Cookie.set('_test', '1');
return (Cookie.erase('_test') === '1');
}
};







5 comments:

Nahum said...

I dont know even if you have tried before a prototype class for the same reason. But some difference the first is JSON base, this is great cause you can manipulate everything with an object.. try a look http://www.lalit.org/lab/jsoncookies/
I had used in a site and work perfect... please take a look and comment,

note: I didnt did the script :)

Tony said...

Wow, what a GREAT SCRIPT!

Thank you very much for telling me about it!... It is actually very easy concept and very very clever its solution.

Thanks!!!

Nahum said...

excellent man, pretty neat isnt it?? pues ojala te sirva un saludo desde Mexico..., acabo de ver que eres de espaƱa... :P ... see ya man...

Tony said...

Gracias man...

David said...

When building the regex pattern as a string, you need to escape any backslashes:

new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)')


The content of this blog is published under a Creative Commons License | RSS Feed
Powered By Blogger