Practical No. 10: Develop a webpage for creating session and persistent cookies.
Cookies
• Cookies are data, stored in small text files, on the computer.
• Cookies remember information about the user like when a user visits a web page, his/her
name can be stored in a cookie, Next time the user visits the page, the cookie
"remembers" his/her name.
Contents of Cookie
Cookies are a plain text data record of 5 variable-length fields −
• Expires − The date the cookie will expire. If this is blank, the cookie will expire
when
the visitor quits the browser.
• Domain − The domain name of your site.
• Path − The path to the directory or web page that set the cookie. This may be
blank if
you want to retrieve the cookie from any directory or page.
• Secure − If this field contains the word "secure", then the cookie may only be
retrieved
with a secure server. If this field is blank, no such restriction exists.
• Name=Value − Cookies are set and retrieved in the form of key-value pairs
CREATING A COOKIE
• JavaScript can create, read, and delete cookies with the document.cookie property.
Eg : document.cookie = "username=John Doe";
• You can also add an expiry date (in UTC time). By default, the cookie is deleted when the
browser is closed:
Eg : document.cookie = "username=John Doe; expires=Thu, 18 Dec 2024 12:00:00 UTC";
• With a path parameter, you can tell the browser what path the cookie belongs to. By
default,
the cookie belongs to the current page.
Eg : document.cookie = "username=John Doe; expires=Thu, 18 Dec 2024 12:00:00
UTC; path=/";
READING A COOKIE
● Reading a cookie is just as simple as writing one, because the value of the
document.cookie the object is the cookie.
• Use this string whenever you want to access the cookie.
• The document.cookie string will keep a list of name=value pairs separated by semicolons,
where name is the name of a cookie and value is its string value.
DELETING A COOKIE
Sometimes you will want to delete a cookie.
• To do this, you just need to set the expiry date to a time in the past.
TYPES OF COOKIE
There are 3 types of Cookies available
1. Session Cookies: They are the cookies which do not have an expiry date. They are
deleted when the browser window is closed
2. Persistent Cookies : They are the cookies which have an expiry date and are deleted
on the date set.
3.Third Party Cookies
Questions.
1.Write a function to delete a cookie.
Ans:
We can delete cookies by following statements
document.cookie=”expires=Thu , 18 Dec 2024 12:00 UTC”;
also
Function to delete a cookie by name function
deleteCookie(name)
{
// Set the cookie with the same name, empty value, and an expiration date in the past
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
}
Exercise:-
1.Write a program to create a session cookie and display content of Cookie.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Practical 10</title>
</head>
<body>
<div>
<span>This is Session Cookies</span>
<div id="Session_Cookies"></div>
<div id="Persistent_Cookies"></div>
</div>
<script type="text/javascript">
// Set a session cookie
document.cookie = "username=student name";
// Display current cookies in the session cookies div
document.getElementById("Session_Cookies").innerHTML = document.cookie;
// Set a persistent cookie with an expiration date
document.cookie = "username=ram; expires=Thu, 18 Dec 2024 12:00:00 UTC";
// Display the updated cookies in the persistent cookies div
document.getElementById("Persistent_Cookies").innerHTML = document.cookie;
// Alert the cookies (optional)
alert(document.cookie);
</script>
</body>
</html>
Output:
2. Write a JavaScript that creates persistent cookies.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Persistent Cookies Example</title>
</head>
<body>
<h1>Persistent Cookie Example</h1>
<button id="setCookie">Set Persistent Cookie</button>
<button id="getCookie">Get Cookie</button>
<div id="cookieValue"></div>
<script type="text/javascript">
// Function to set a persistent cookie
function setPersistentCookie(name, value, days) {
// Create a new Date object for expiration
const expires = new Date();
// Calculate the expiration time in milliseconds
expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000)); // Days to
milliseconds
// Set the cookie with name, value, expiration date, and path
document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/`;
}
// Function to retrieve the value of a cookie by name
function getCookie(name) {
const nameEQ = name + "="; // Create a string to search for
// Split document.cookie into individual cookies
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim(); // Trim whitespace
// Check if the current cookie starts with the desired name
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length); // Return the cookie value
}
}
return null; // Return null if the cookie is not found
}
// Event listener for the "Set Persistent Cookie" button
document.getElementById('setCookie').addEventListener('click', () => {
// Call the setPersistentCookie function with name, value, and expiration days
setPersistentCookie('username', 'student', 7); // Set cookie for 7 days
alert('Persistent cookie has been set!'); // Alert user that the cookie is set
});
// Event listener for the "Get Cookie" button
document.getElementById('getCookie').addEventListener('click', () => {
// Call the getCookie function and store the result
const cookieValue = getCookie('username');
// Display the cookie value or a message if not found
document.getElementById('cookieValue').innerText = cookieValue ? `Cookie value: $
{cookieValue}` : 'Cookie not found.';
});
</script>
</body>
</html>