How can I list all cookies for the current page with Javascript?

后端 未结 8 1482
日久生厌
日久生厌 2020-12-13 01:34

Is there any way to, with help of Javascript, list all cookies associated with the current page? That is, if I don\'t know the names of the cookies but want to retrieve all

8条回答
  •  半阙折子戏
    2020-12-13 02:11

    Many people have already mentioned that document.cookie gets you all the cookies (except http-only ones).

    I'll just add a snippet to keep up with the times.

    document.cookie.split(';').reduce((cookies, cookie) => {
      const [ name, value ] = cookie.split('=').map(c => c.trim());
      cookies[name] = value;
      return cookies;
    }, {});
    

    The snippet will return an object with cookie names as the keys with cookie values as the values.

    Slightly different syntax:

    document.cookie.split(';').reduce((cookies, cookie) => {
      const [ name, value ] = cookie.split('=').map(c => c.trim());
      return { ...cookies, [name]: value };
    }, {});
    

提交回复
热议问题