How to get all the cookies from the browser

mahabub.devs3
Mahabubur Rahman
Published on Sep, 20 2024 1 min read 0 comments
image

The topic is to get all the cookies stored in current domain .We can't get all cookies for security reasons. Browser each domain has a separate cookie.

We will address this issue below:

We know that browser cookie store in document.cookie. So using document.cookie we can get browser domain cookies. Now we will solve this problem by some steps.

Steps:

  1. Access cookies using document.cookie.
  2. Split the cookie string by ';' to get cookie in an array.
  3. Iterate the array to get each element;
  4. Append every cookie by key value in a object.

 

So all step is in the following function - 

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

 

Output: Base on browser cookies you will get some cookie data as bellow -

{
_ga: "GA1.1.2025035515.1627551003"
_ga_TQZJ9EJW3C: "GS1.1.1628186027.4.1.1628186083.0"
_gcl_au: "1.1.1554616670.1627551003"
}

 

 

 

0 Comments