How to get and set cookies in JavaScript

后端 未结 2 1770
谎友^
谎友^ 2021-01-03 16:44

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

Set: document.cookie = \"=[;expires=[;path=

相关标签:
2条回答
  • 2021-01-03 17:26

    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.

    0 讨论(0)
  • 2021-01-03 17:33

    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);
          }
      }
    }
    
    0 讨论(0)
提交回复
热议问题