Tags
Asked 2 years ago
17 Jun 2021
Views 211
Breanna

Breanna posted

Set cookie and get cookie with JavaScript

Set cookie and get cookie with JavaScript
sqltreat

sqltreat
answered Apr 27 '23 00:00

Sure! Here's an example of how to set and get a cookie in JavaScript:

Setting a cookie
To set a cookie, you can simply assign a string with the cookie name, value, and optional attributes to the document.cookie property. Here's an example of how to set a cookie with a name " myCookie " and a value "myValue", that expires in one day:



document.cookie = "myCookie=myValue; expires=Wed, 28 Apr 2023 00:00:00 UTC; path=/";

In this example, the cookie is created by setting the document.cookie property to a string that consists of the cookie name, followed by an equal sign and the cookie value. The expires attribute sets the cookie's expiration date, and the path attribute specifies the URL path for which the cookie is valid.

Getting a cookie
To get a cookie, you can read the document.cookie property, which returns a string containing all cookies for the current domain. You can then parse the string to find the value of a specific cookie. Here's an example of how to get the value of a cookie with the name "myCookie":



const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
  const cookie = cookies[i].trim();
  if (cookie.startsWith('myCookie=')) {
    const myCookieValue = cookie.substring('myCookie='.length);
    console.log(myCookieValue);
  }
}

In this example, the document. cookie property is split into an array of individual cookies. Then, each cookie is checked to see if it starts with the name " myCookie ". If a matching cookie is found, the code extracts its value and logs it to the console.

Note that cookies are stored as strings and have a limited size, so it's important to encode any data you store in them properly to avoid data loss or security issues. Additionally, make sure to be mindful of any privacy implications of setting cookies, and only use them when necessary for your application.
Post Answer