Skip to content

Instantly share code, notes, and snippets.

@Witiko
Created September 6, 2013 11:05
Show Gist options
  • Save Witiko/6462415 to your computer and use it in GitHub Desktop.
Save Witiko/6462415 to your computer and use it in GitHub Desktop.
A cookie interfacing library
/*
EasyCookie library
A lightweight solution for basic cookies handing
Copyright (C) 2010 Vít Novotný
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Usage:
Global Object / Boolean false cookie
cookie.save(name, data);
cookie.load[name];
cookie.erase(name);
cookie.length
*/
var cookie = (navigator.cookieEnabled && (function(){
var text = Date.now?Date.now():new Date().getTime(),
current = new Date(),
expired = new Date();
current.setTime(text + 3155692597470);
current = current.toUTCString();
expired.setTime(text - 1);
expired = expired.toUTCString();
document.cookie = text + "=" + text + ";expires=" + current + ";domain=" + location.hostname + ";path=/";
var returnValue = !!document.cookie.match('(^|;) ?' + text + '=([^;]*)(;|$)');
document.cookie = text + "=" + text + ";expires=" + expired + ";domain=" + location.hostname + ";path=/";
return returnValue;
})())?(function() {
var text = Date.now?Date.now():new Date().getTime(),
current = new Date(),
expired = new Date(),
loaded = {}, length = 0;
current.setTime(text + 3155692597470);
current = current.toUTCString();
expired.setTime(text - 1);
expired = expired.toUTCString();
return {
save : function(name, data) {
document.cookie = name + "=" + data + ";expires=" + current + ";domain=" + location.hostname + ";path=/";
if(!(name in cookie.load))
cookie.length++;
cookie.load[name] = data;
return !!document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
},
erase : function(name) {
if(!(name in cookie.load)) return false;
document.cookie = name + "=" + name + ";expires=" + expired + ";domain=" + location.hostname + ";path=/";
delete cookie.load[name];
cookie.length--;
return !document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
},
load : (function(){
var split = document.cookie.split(";"),
processing;
for(var i = 0, l = split.length; i < l; i++) {
processing = split[i].split("=");
loaded[processing[0]] = processing[1];
length++;
}
return loaded;
})(),
length : length
}
})():false;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment