Css Practical No - 10
Css Practical No - 10
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
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
TYPES OF COOKIE
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";
Output:
<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=/`;
}