Skip to content

Instantly share code, notes, and snippets.

@avil13
Last active December 27, 2017 15:59
Show Gist options
  • Save avil13/82be1340c5c4664239a2 to your computer and use it in GitHub Desktop.
Save avil13/82be1340c5c4664239a2 to your computer and use it in GitHub Desktop.
JavaScript cookie function
/**
* myCookie('test', 123123) // set cookie
* myCookie('test') // get cookie
* myCookie('test', false) // delete cookie
*/
function myCookie(name, value) {
name = encodeURIComponent(name);
if (value === undefined) {
// if value - empty then return cookie
var results = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
var res = results ? unescape(results[2]) : 'null';
try {
res = JSON.parse(res);
} catch (e) {
res += '';
}
return res; // возвращаем полученное значение
}
var cookie_string = '';
if (value === false) {
// delete cookie
cookie_string = name + '=\'\'; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/; ';
} else {
cookie_string = name + '=' + encodeURIComponent(JSON.stringify(value));
var expires = new Date();
expires.setFullYear(expires.getFullYear() + 1);
cookie_string += '; expires=' + expires.toGMTString();
cookie_string += '; path=/; ';
}
document.cookie = cookie_string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment