如何在JavaScript中获取和设置Cookie

时间:2018-07-12 19:17:45

标签: javascript cookies

通过JavaScript获取和设置Cookie有点像这样:

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

获取:解析document.cookie

我在W3C.org Cookies上找到了此获取和设置功能

是否有更优雅/更轻松的方法来做到这一点?

2 个答案:

答案 0 :(得分:6)

您可以使用一些简单的功能,例如setCookie()getCookie()

您可以使用以下电话设置Cookie:

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;
}

注意:来源来自quirksmode。如果您想了解有关Cookie的更多信息,请查看docs

答案 1 :(得分:2)

ES6方法是:

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);
      }
  }
}