Read cookies with JavaScript

前端 未结 3 1483
既然无缘
既然无缘 2020-12-06 14:42

I know how to write/create cookies in JavaScript.........................................................

//Create the cookies
document.cookie = \"Name=\" +          


        
相关标签:
3条回答
  • 2020-12-06 15:23

    Referring to document.cookie gets you the whole string of cookies. They're separated by semicolons.

    var cookies = document.cookie.split(';'); // "cookies" will be an array
    

    You could then make that an object with name->value mapping:

    var cookieMap = {};
    for (var i = 0; i < cookies.length; ++i) {
      cookies[i].replace(/^\s*([^=]+)=(.*)$/, function(_, name, val) {
        cookieMap[name] = unescape(val);
      });
    }
    

    Now you can look at a cookie "mycookie" like this:

    var mycookieVal = cookieMap.mycookie;
    

    note this is been edited since its initial broken version - still the same idea but not it should actually work. The idea is that the loop takes each of the parts of document.cookie that were separated by semicolons, and then further splits each of those into a name part (stuff before the "=", except leading spaces) and a "value" part (stuff after the "=" to the end of the cookie part). The value is then stored in the "cookieMap" under the given name.

    0 讨论(0)
  • 2020-12-06 15:38

    These are much *much* better references than w3schools (the most awful web reference ever made):

    • http://www.quirksmode.org/js/cookies.html
    • https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

    Examples derived from these references:

    // sets the cookie cookie1
    document.cookie =
     'cookie1=test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'
    
    // sets the cookie cookie2 (cookie1 is *not* overwritten)
    document.cookie =
     'cookie2=test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'
    
    // remove cookie2
    document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'
    

    The mozilla reference even has a nice cookie library you can use.

    0 讨论(0)
  • 2020-12-06 15:43

    From http://w3schools.com/js/js_cookies.asp

    set cookie

    function setCookie(c_name,value,expiredays)
    {
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
    }
    

    get cookie

    function getCookie(c_name)
    {
    if (document.cookie.length>0)
      {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1)
        {
        c_start=c_start + c_name.length+1;
        c_end=document.cookie.indexOf(";",c_start);
        if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
        }
      }
    return "";
    }
    
    0 讨论(0)
提交回复
热议问题