SirPilan
SirPilan

Reputation: 4857

How to get and set cookies in JavaScript

Getting and setting Cookies via JavaScript feels a little odd like this:

Set: document.cookie = "<key>=<value>[;expires=<utc_expires>[;path=<path>]]";

Get: parse document.cookie

I found this get and set function on W3C.org Cookies

Is there a more elegant/easy way to do this?

Upvotes: 4

Views: 41771

Answers (2)

ofcyln
ofcyln

Reputation: 88

ES6 approach is:

const setCookie = (cookieKey, cookieValue, expirationDays) => {
  let expiryDate = '';

  if (expirationDays) {
    const date = new Date();

    date.setTime(`${date.getTime()}${(expirationDays || 30 * 24 * 60 * 60 * 1000)}`);

    expiryDate = `; expiryDate=" ${date.toUTCString()}`;
  }

  document.cookie = `${cookieKey}=${cookieValue || ''}${expiryDate}; path=/`;
}

const getCookie = (cookieKey) => {
  let cookieName = `${cookieKey}=`;

  let cookieArray = document.cookie.split(';');

  for (let cookie of cookieArray) {

    while (cookie.charAt(0) == ' ') {
          cookie = cookie.substring(1, cookie.length);
      }

    if (cookie.indexOf(cookieName) == 0) {
          return cookie.substring(cookieName.length, cookie.length);
      }
  }
}

Upvotes: 6

user3596335
user3596335

Reputation:

You can use some simple functions like setCookie() and getCookie().

You can set a cookie using the call:

setCookie('myName','value', 3);

function setCookie(name, value, days) {
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

function getCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var 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;
}

Note: Source is from quirksmode. Please have a look at the docs if you want to know more about cookies.

Upvotes: 22

Related Questions