Tags
Asked 3 years ago
17 Jun 2021
Views 203
Jarrell

Jarrell posted

How to get cookies from Javascript?

How to get cookies from Javascript?
sandip

sandip
answered Apr 27 '23 00:00

To get cookies from JavaScript, you can use the document.cookie property. This property returns a semicolon-separated string of all the cookies for the current domain.

Here's an example of how you can use document.cookie to get the value of a specific cookie:



// get the value of a cookie by name
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);
    }
  }
  return null;
}

// usage example
const myCookie = getCookie('myCookieName');
console.log(myCookie);

This code defines a function called getCookie that takes a cookie name as an argument and returns the cookie value if found. It does this by splitting the document. cookie string into an array of individual cookies, then looping through each cookie and checking if it starts with the desired name. If a matching cookie is found, the function returns its value.

Note that document.cookie only provides access to cookies that are visible to the current page, meaning cookies that have been set for the current domain and path. If you need to access cookies from a different domain or path, you may need to use a different approach.
Post Answer