Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Created July 12, 2015 02:25
Show Gist options
  • Save wpscholar/a932b38945f381c730ca to your computer and use it in GitHub Desktop.
Save wpscholar/a932b38945f381c730ca to your computer and use it in GitHub Desktop.
Functions for setting, getting and deleting cookies via JavaScript
/**
* Set a cookie
*
* @param {string} cookieName
* @param {string} cookieValue
* @param {object} cookieOptions (expires, domain, path)
*/
function setCookie(cookieName, cookieValue, cookieOptions) {
cookieOptions = cookieOptions || {};
if (cookieValue) {
if (cookieOptions.expires) {
var d = new Date();
d.setTime(d.getDate() + cookieOptions.expires);
cookieValue += '; expires=' + d.toUTCString();
}
if (cookieOptions.domain) {
cookieValue += "; domain=" + cookieOptions.domain;
}
if (cookieOptions.path) {
cookieValue += "; path=" + cookieOptions.path;
}
document.cookie = cookieName + '=' + cookieValue;
}
}
/**
* Get the value for a specific cookie
*
* @param {string} cookieName
* @param {string|null} defaultValue
* @returns {string}
*/
function getCookie(cookieName, defaultValue) {
if (typeof defaultValue === 'undefined') {
defaultValue = null;
}
cookieName += "=";
var cookieCollection = document.cookie.split(';');
for (var i = 0; i < cookieCollection.length; i++) {
var c = cookieCollection[i].trim();
if (c.indexOf(cookieName) === 0) {
return c.substring(cookieName.length, c.length);
}
}
return defaultValue;
}
/**
* Delete a cookie
*
* @param cookieName
*/
function deleteCookie(cookieName) {
var value = getCookie(cookieName);
setCookie(cookieName, value, -1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment