如何在 JavaScript 中获取和设置 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51312980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:30:20  来源:igfitidea点击:

How to get and set cookies in JavaScript

javascriptcookies

提问by Pilan

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

通过 JavaScript 获取和设置 Cookie 感觉有点奇怪,如下所示:

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

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

Get: parse document.cookie

获取:解析document.cookie

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

我在W3C.org Cookies上发现了这个 get 和 set 函数

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

有没有更优雅/简单的方法来做到这一点?

回答by

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

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

You can set a cookie using the call:

您可以使用以下调用设置 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;
}

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

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

回答by ofcyln

ES6 approach is:

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