Skip to content

Instantly share code, notes, and snippets.

@jimboobrien
Forked from wpscholar/cookies.js
Created September 20, 2017 22:42
Show Gist options
  • Save jimboobrien/1d342e1ffe6e70053456bab81e1b1b92 to your computer and use it in GitHub Desktop.
Save jimboobrien/1d342e1ffe6e70053456bab81e1b1b92 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