Get cookies by name in javascript

How to create and read cookies in JavaScript

An HTTP cookie (also known as web cookie, browser cookie) is a small piece of information stored by the server in the user’s browser. Cookies are commonly used for session management, user-tracking, and storing user preferences.

In JavaScript, you can use the document.cookie property to create, read, and delete cookies. Note that the document.cookie property can only access cookies with the HttpOnly attribute unspecified.

document.cookie = 'name=John Doe' 

Since the cookie value can not contain semicolons, commas, or spaces, you need the encodeURIComponent() function to encode the value before storing it in the cookie:

document.cookie = `name=$encodeURIComponent('John Doe')>` 

Note: When you set the value of document.cookie , the web browser does not overwrite existing cookies. Instead, it adds a new HTTP cookie to the user’s computer.

By default, the above cookie lifespan is the current browser session, which means that it is removed when the user closes the browser. Such cookies are called session cookies. To persist cookies beyond the current browser session, you need to specify its expiry date either using the expires attribute (in UTC/GMT format) or the max-age attribute (in seconds):

// Set cookie fixed expiration date document.cookie = `name=$encodeURIComponent('John Doe')>; expires=Sun, 14 August 2022 03:11:45 UTC` // Set cookie max age, e.g. expire after 7 days document.cookie = `name=$encodeURIComponent('John Doe')>; max-age=$7 * 24 * 60 * 60>` 

By default, a cookie is available to all web pages in the same directory and its subdirectories. However, you can explicitly specify a path attribute to ensure that the cookie is only accessible to that path and its subdirectories. For example, if set the path to / , the cookie will be available throughout the website regardless of which page creates it:

document.cookie = `name=$encodeURIComponent('John Doe')>; path=/` 

The cookies, by default, are available only to the web pages in the domain they were used to set in. However, you can use the domain attribute to make a cookie available across subdomains. For exmaple, if a cookie created by a web page on help.example.com sets its path to / and its domain to example.com , that cookie is also available to all web pages on blog.example.com , dash.example.com , etc.

document.cookie = `name=$encodeURIComponent('John Doe')>; path=/; domain=example.com` 

You can also make a cookie secure using the secure attribute. Such cookies are only transmitted over a secure (i.e. encrypted) connection such as HTTPS:

document.cookie = `name=$encodeURIComponent('John Doe')>; path=/; domain=example.com; secure` 

Finally, let us write a JavaScript function that takes in the name, value, expiry days, path, and domain, and adds an HTTP cookie:

const setCookie = (name, value, days, path, domain, secure) =>  let cookie = `$name>=$encodeURIComponent(value)>` // Add expiry date if (days)  const expiry = new Date() expiry.setDate(expiry.getDate() + days) cookie += `; expires=$expiry.toUTCString()>` > // Add Path, Domain, and Secure if (path) cookie += `; path=$path>` if (domain) cookie += `; domain=$domain>` if (secure) cookie += `; secure` // Set an HTTP cookie document.cookie = cookie > 
setCookie('name', 'John Doe', 90); 

The document.cookie property returns all cookies set by the server as a series of key-value pairs separated by semi-colons:

const cookies = document.cookie console.log(cookies) // _ga=GA1.2.315746813.1624003242; lesson_completed=false; theme=dark 

Since all the values and names are URL-encoded, you have to decode them using the decodeURIComponent() method. Let us write a function that takes the cookie name as input and returns its value. If the cookie is not found, it should return a null value.

const getCookie = name =>  const cookies = document.cookie.split(';') for (let i = 0; i  cookies.length; i++)  let c = cookies[i].trim().split('=') if (c[0] === name)  return decodeURIComponent(c[1]) > > return '' > console.log(getCookie('_ga')) // GA1.1.1736818142.1621579881 

The above code uses the JavaScript split() method to split the cookie string by semi-colon. Then it iterates through the result array to match the name of the requested cookie with the key-value pairs.

You can update a cookie in the same way as you create it with the same name, path, domain, and secure option:

document.cookie = 'name=Alex; expires=Mon, 15 August 2022 10:52:32 UTC' 

Deleting a cookie is very simple. All you need to do is set the expiration date to some time in the past with the same name, path, domain, and secure option:

document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC" 

Read Next: How to use cookies in Spring Boot ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Cookies are data chunks stored on a system by a web browser. They are often used to store user preferences, login information, and other types of data that can be utilized to personalize a user’s experience on a website. Cookies are typically stored as key-value pairs, where the key is a unique identifier for the cookie, and the value is the data that the cookie stores.

This post is all about getting the cookie by utilizing its name in JavaScript.

To get the value of a cookie with a specific name in JavaScript, use the “getCookie()” function. This function takes a cookie name as a parameter and returns the value of the cookie if it exists or null if the cookie does not exist.

Example

In the given example, we will first set the cookie and then get it by name. So, first, create two buttons, “SetCookie” and “GetCookie”, in an HTML file and attach onclick events that will invoke the function on the button click:

Define a function “setCookie()” to set the cookie on the browser using the “document.cookie” attribute:

document. cookie = «cookiename=cookie;expires=Tues, 27 Dec 2022 12:30:00 UTC» ;

Now, define a function called “getCookie()” by passing “name” as a parameter to get the cookie by name. Verify whether the cookie is present using the “length” attribute. If its length is not equal to zero, split the cookie string based on separator “=” and print the name and its value in an alert message:

functiongetCookie ( name ) {
if ( document. cookie . length != 0 ) {
var array = document. cookie . split ( «=» ) ;
alert ( «Name=» + array [ 0 ] + » » + «Value=» + array [ 1 ] ) ;
}
else {
alert ( «Cookie not available» ) ;
}
}

Call the “getCookie()” function by passing the name of the cookie as “cookiename”:

It can be observed that the cookie is first set and then its value is fetched using the cookie name:

That’s all about getting the cookie by name in JavaScript.

Conclusion

Use the “getCookie()” function by passing the “name” as a parameter, check if the cookie length is not equal to zero, split the cookie string using the “split()” method by passing a separator, and get the value of the cookie on the specified name. Note that this function will only perform its functionality if the cookie is set in the current page’s domain. This post defined the procedure for getting the cookie by name in JavaScript.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Читайте также:  Inherit and initial css
Оцените статью