Skip to content

Instantly share code, notes, and snippets.

@jgodson
Created June 21, 2020 15:27
Show Gist options
  • Save jgodson/592ca8a6b5455fd49ef982cbd24322ac to your computer and use it in GitHub Desktop.
Save jgodson/592ca8a6b5455fd49ef982cbd24322ac to your computer and use it in GitHub Desktop.
Functions to manipulate cookies for various purposes
window.Cookies = window.Cookies || {};
// Prevent IE8-9 silent errors
if (!window.console) {
  window.console = {
    warn: function() {}
  }
}
/*
** Sets a cookie
** @params name {string} - name of the cookie
**         value {string} - value to store for the cookie
**         expiry {string?|number?} - "5 days|minutes|hours". Only a number defaults to 'minutes'
*/
Cookies.setCookie = function(name, value, expiry) {
  // Set the expiry (if specified, otherwise just a session cookie)
  if (expiry) {
    // Do some checking to see if format is right
    if (typeof expiry === 'string' && expiry.split(' ').length === 2) {
      // Split expiry into two parts [time, type (days|minutes|hours)]
      expiry = expiry.split(' ');
      var expiryTime = parseInt(expiry[0]);
      // Check to see if the time is a valid number
      if (parseInt(expiryTime)) {
        var expiryType = typeof expiry[1] === 'string' ? expiry[1].toLowerCase() : 'days';
        switch (expiryType) {
          case 'days':
          case 'day':
            expiryTime *= 24 * 60 * 60 * 1000;
            break;
          case 'hours':
          case 'hour':
            expiryTime *= 60 * 60 * 1000;
            break;
          // 'minutes' (or anything else)
          default:
            expiryTime *= 60 * 1000;
            break;
        }
      } else {
        console.warn("Not a valid number for expiry on cookie '" + name + "'");
      }
    } else if (parseInt(expiry)) {
      // Check if it parses to a number and then default to minutes (x * 60 * 1000)
      var expiryTime = expiry * 60 * 1000;
    } else {
      console.warn("Expiry given for '" + name + "' is not valid.");
    }
  }
  // Build the cookie
  newCookie = name + "=" + value + ";";
  if (expiryTime) {
    var timeNow = new Date();
    timeNow.setTime(timeNow.getTime() + expiryTime);
    newCookie += "expires=" + timeNow.toUTCString() + ";";
  }
  newCookie += "path=/;";
  // Set the cookie
  document.cookie = newCookie;
}
/*
** Make a cookie expire immediately (effectively deleting it)
** @params name {string} - name of cookie to delete
*/
Cookies.deleteCookie = function(name) {
  document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;";
};
/*
** Gets the value from a given cookie
** @params name {string} - name of the cookie
** @returns {any} - value of the cookie or 'undefined' if cookie does not exist
*/
Cookies.getCookie = function(name) {
  var cookieArray = document.cookie.split(';');
  for(var i = 0; i < cookieArray.length; i++) {
    var cookie = cookieArray[i].split("=", 2);
    cookie[0] = cookie[0].replace(/^\s+/, "");
    if (cookie[0] == name) {
      return cookie[1];
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment