Read cookies with JavaScript

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

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

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


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题