I need to get all the cookies from the browser

前端 未结 9 1295
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 09:52

I need to get all the cookies stored in my browser using JavaScript. How can it be done?

相关标签:
9条回答
  • 2020-12-04 10:44

    Added trim() to the key in object, and name it str, so it would be more clear that we are dealing with string here.

    export const getAllCookies = () => document.cookie.split(';').reduce((ac, str) => Object.assign(ac, {[str.split('=')[0].trim()]: str.split('=')[1]}), {});
    
    0 讨论(0)
  • 2020-12-04 10:48
    1. You can't see cookies for other sites.
    2. You can't see HttpOnly cookies.
    3. All the cookies you can see are in the document.cookie property, which contains a semicolon separated list of name=value pairs.
    0 讨论(0)
  • 2020-12-04 10:49

    You can only access cookies for a specific site. Using document.cookie you will get a list of escaped key=value pairs seperated by a semicolon.

    secret=do%20not%20tell%you;last_visit=1225445171794
    

    To simplify the access, you have to parse the string and unescape all entries:

    var getCookies = function(){
      var pairs = document.cookie.split(";");
      var cookies = {};
      for (var i=0; i<pairs.length; i++){
        var pair = pairs[i].split("=");
        cookies[(pair[0]+'').trim()] = unescape(pair.slice(1).join('='));
      }
      return cookies;
    }
    

    So you might later write:

    var myCookies = getCookies();
    alert(myCookies.secret); // "do not tell you"
    
    0 讨论(0)
提交回复
热议问题