Tags
Asked 3 years ago
17 Jun 2021
Views 234
Bailee

Bailee posted

Read cookies with JavaScript

Read cookies with JavaScript
kiran

kiran
answered Apr 27 '23 00:00

You can read cookies with JavaScript using the document.cookie property, which returns a string containing all the cookies for the current document. Here's an example:



const cookies = document.cookie;
console.log(cookies);

This will log all the cookies for the current document to the console.

To read a specific cookie, you can use the following function:



function getCookie(name) {
  const cookies = document.cookie.split(';');
  for (let i = 0; i < cookies.length; i++) {
    const cookie = cookies[i].trim();
    if (cookie.startsWith(name + '=')) {
      return cookie.substring(name.length + 1, cookie.length);
    }
  }
  return null;
}

This function takes the name of the cookie as a parameter, splits the document.cookie string into an array of individual cookies, and loops through the array looking for a cookie with a name that matches the parameter. If a match is found, it returns the value of the cookie. If no match is found, it returns null.

Here's an example of how to use the getCookie function:


const myCookie = getCookie('myCookieName');
if (myCookie) {
  console.log('Value of myCookieName:', myCookie);
} else {
  console.log('myCookieName not found');
}
Post Answer