Skip to content

Instantly share code, notes, and snippets.

@deitch
Created April 1, 2015 09:31
Show Gist options
  • Save deitch/dea1a3a752d54dc0d00a to your computer and use it in GitHub Desktop.
Save deitch/dea1a3a752d54dc0d00a to your computer and use it in GitHub Desktop.
setCookie()
var setCookie = function (key, value, options) {
var result = null, decode, days, t, i, pair, pairs, opts = options;
// key and value given, set cookie...
if (arguments.length > 1 && (value === null || typeof(value) !== "object")) {
opts = opts || {};
if (value === null) {
opts.expires = -1;
}
if (typeof opts.expires === 'number') {
days = opts.expires;
t = opts.expires = new Date();
t.setDate(t.getDate() + days);
}
document.cookie = [
encodeURIComponent(key), '=',
opts.raw ? String(value) : encodeURIComponent(String(value)),
opts.expires ? '; expires=' + opts.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
'; path='+(opts.path||'/'),
opts.domain ? '; domain=' + opts.domain : '',
opts.secure ? '; secure' : ''
].join('');
return (document.cookie);
}
// key and possibly options given, get cookie...
opts = value || {};
decode = opts.raw ? function (s) { return s; } : decodeURIComponent;
pairs = document.cookie.split('; ');
for (i = 0; i<pairs.length ; i++) {
pair = pairs[i] && pairs[i].split('=');
if (decode(pair[0]) === key) { result = decode(pair[1] || ''); i = pairs.length;} // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
}
return (result);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment