乐闻世界logo
搜索文章和话题

How do I create and read a value from cookie with javascript?

1个答案

1

Handling cookies in JavaScript primarily involves the following steps: creation, reading, and setting expiration dates. I will explain each step in detail, providing corresponding code examples.

Creating Cookies

We can use the document.cookie property to create cookies. Creating cookies primarily involves assigning a value to document.cookie, which is a string that typically includes the cookie's name, value, and other optional attributes (such as expiration date, path, and domain).

javascript
function setCookie(name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; }

In this example, the setCookie function accepts three parameters: name (the cookie's name), value (the cookie's value), and days (the cookie's expiration period in days). If the days parameter is provided, we calculate the specific expiration date and set it. Finally, we set the cookie in the browser using document.cookie.

Reading Cookies

Reading cookies involves using the document.cookie property. This property contains a string that includes all cookies set for the current domain (name and value). We need to write a function to parse this string to retrieve the value of the specific cookie we're interested in.

javascript
function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; }

This getCookie function searches for a cookie matching the specified name. It iterates through all cookies by splitting the document.cookie string and checks if each cookie's name matches the provided name.

When creating cookies, we already covered setting expiration dates using the expires attribute within the setCookie function. To delete a cookie, simply set its expiration time to a past date.

javascript
function deleteCookie(name) { document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/'; }

This deleteCookie function sets the cookie's expiration time to January 1, 1970 (a past date), causing the browser to remove the cookie.

These are the fundamental operations for working with cookies in JavaScript. I hope this helps you understand how to handle cookies in web applications.

2024年8月12日 11:21 回复

你的答案