davevasquez
10/6/2017 - 5:43 PM

Create & Read Cookies

A set of simple pure-Javascript functions for creating and reading cookies. These are cleaned up and converted for easy inclusion in a Vue component. Credit to Hiljá Studio for the original functions: http://clubmate.fi/setting-and-reading-cookies-with-javascript/

createCookie(name, value, days) {
  let expires = '';

  if (days) {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = `; expires=${date.toGMTString()}`;
  } else {
    expires = '';
  }
  document.cookie = `${name}=${value}${expires}; path=/`;
},

// Read cookie
readCookie(name) {
  const nameEQ = `${name}=`;
  const ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i += 1) {
    let c = ca[i];
    while (c.charAt(0) === ' ') {
      c = c.substring(1, c.length);
    }
    if (c.indexOf(nameEQ) === 0) {
      return c.substring(nameEQ.length, c.length);
    }
  }
  return null;
},