How to use document.cookie In Javascript
In this approach, we are using the document.cookie property to both set and retrieve cookies. When setting a cookie, we assign a string formatted as âname=valueâ to document.cookie, and to retrieve cookies, we split the cookie string and parse it into a key-value map.
Syntax:
document.cookie = "username=name;
expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";
Example: The below example uses document.cookie to set and retrieve cookies using JavaScript.
<!DOCTYPE html>
<head>
<title>Example 1</title>
</head>
<body>
<h1 style="color: green;">
w3wiki
</h1>
<h3>Using document.cookie</h3>
<input type="text" id="uInput"
placeholder="Enter cookie value">
<button onclick="setFn()">
Set Cookie
</button>
<button onclick="getFn()">
Get Cookie
</button>
<p id="cookieVal"></p>
<script>
function setFn() {
const value =
document.getElementById('uInput').value;
document.cookie =
`exampleCookie=${value}`;
alert('Cookie has been set!');
}
function getFn() {
const cookies =
document.cookie.split('; ');
const cookieMap = {};
cookies.forEach(cookie => {
const [name, value] = cookie.split('=');
cookieMap[name] = value;
});
const cookieVal = cookieMap['exampleCookie'];
document.getElementById('cookieVal').textContent =
`Cookie Value: ${cookieVal}`;
}
</script>
</body>
</html>
Output:
How to Set & Retrieve Cookies using JavaScript ?
In JavaScript, setting and retrieving the cookies is an important task for assessing small pieces of data on a userâs browser. This cookie can be useful for storing user preferences, session information, and many more tasks.
Table of Content
- Using document.cookie
- Using js-cookie library
Contact Us