Unit 4 Cookies and Browser Data
Unit 4 Cookies and Browser Data
Cookies in JavaScript are small pieces of data stored on the client-side by the
browser.
They can be used to store user preferences, session data, or other small
amounts of information
Cookie contains information as string generally in the form of name-value pairs
separated by semi-colons
Types of Cookie
1. Session Cookies
Definition: These cookies are temporary and are deleted when the
browser is closed.
Use Case: They are used to store information that should only persist
during the user's session, such as login status or shopping cart contents.
Example: If you don't set an expiration date for a cookie, it becomes a
session cookie.
document.cookie = "sessionToken=abc123; path=/;";
2. Persistent Cookies
Definition: These cookies remain on the user's device for a specified
period or until they are deleted manually.
Use Case: They are used to remember user preferences, login details, or
other information across sessions.
Example: You set an expiration date or a maximum age to make a cookie
persistent.
let date = new Date();
3. Third-Party Cookies
Definition: These cookies are set by a domain other than the one the
user is currently visiting, typically through embedded content like ads or
social media widgets.
Use Case: They are often used for tracking and advertising purposes.
Example: A third-party cookie might be set by an ad network to track
user behaviour across multiple sites.
Cookie Variable
In JavaScript, cookies are typically managed using the document.cookie property. When
setting a cookie, you can specify several attributes like Expires, Domain, Path, Secure, and
the Name=Value
1. Name=Value
This is the basic structure of a cookie.
Name: The name of the cookie.
Value: The value associated with the cookie
Ex:
document.cookie = "username=Samarth";
2. Expires
Defines the expiration date of the cookie. After this date, the cookie is no longer valid.
The date must be in the UTC/GMT format.
Ex:
document.cookie = "username=Samarth; expires=Fri, 31 Dec 2024 23:59:59 GMT";
Without the expires attribute, the cookie will be a session cookie and will be deleted when
the browser is closed.
3. Domain
Specifies the domain that can access the cookie.
If not specified, the cookie is available only to the domain that set it.
Ex:
document.cookie = "username=Samarth; domain=example.com";
4. Path
Specifies the URL path that must exist in the requested URL for the browser to send
the cookie.
By default, the path is the page that set the cookie.
Ex:
document.cookie = "username=Samarth; path=/admin";
5. Secure
If set, the cookie will only be sent over secure (HTTPS) connections.
Example:
document.cookie = "username=Samarth; secure";
Full Example:
set a cookie with all of these attributes:
document.cookie = "username=Samarth; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/;
domain=example.com; secure";
//Writing/Storing Cookie
The simplest way to to create cookie is to assign value to document.cookie
object.
Syntax:
document.cookie="key1=value1;key2=value2;expires=date";
here expire attribute is optional, if you provide the attribute with a valid date
and time then cookie will expire on given data and time , thereafter cookie will
not be accessible.
<html>
<body>
Enter Name<br>
<input type="text" id="nm" >
<br>
Enter Value<br>
<input type="text" id="vl" >
<br>
<br>
<input type="button" onclick="writeCookie()" value="writeCookie">
<br>
<br>
<input type="button" onclick="readCookie()" value="readCookie">
<br>
<script>
function writeCookie()
{
name=document.getElementById("nm").value;
value=document.getElementById("vl").value;
cookie_str=name+"="+value+";";
document.cookie=cookie_str;
}
function readCookie()
{
cookie_str=document.cookie;
cookieArray=cookie_str.split(";");
for(i=0;i<cookieArray.length;i++)
{
element=cookieArray[i].split("=");
document.write("<br> Cookie Name "+element[0]);
document.write("<br> Cookie Value "+element[1]);
}
}
</script>
</body>
</html>
//Creating Cookie
In JavaScript, we can create,read,update and delete a cookie by using
document.cookie property.
This property represent all the cookies associated with a document.
To create or store new cookie, assign a name=value string to this property.
Syntax
document.cookie=="name=value;”
<html>
<body>
Enter Name<br>
<input type="text" id="nm" >
<br>
Enter Value<br>
<input type="text" id="vl" >
<br>
<br>
<input type="button" onclick="createCookie()" value="createCookie">
<br>
<br>
<input type="button" onclick="readCookie()" value="readCookie">
<br>
<script>
function createCookie()
{
name=document.getElementById("nm").value;
value=document.getElementById("vl").value;
cookie_str=name+"="+value+";";
document.cookie=cookie_str;
}
function readCookie()
{
cookie_str=document.cookie;
cookieArray=cookie_str.split(";");
for(i=0;i<cookieArray.length;i++)
{
element=cookieArray[i].split("=");
document.write("<br> Cookie Name "+element[0]);
document.write("<br> Cookie Value "+element[1]);
}
}
</script>
</body>
</html>
//Deleting Cookies
By default, cookie disappears when the browser is closed, such type of cookies
are called “session cookies”
To survive the cookie, we can set either the expires or max-age option.
Deleting using expires variable
JavaScript program that deletes a cookie using the Expires attribute by setting
the expiration date to a past date (which immediately invalidates the cookie):
Ex:
<html>
<body>
<script>
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC;
path=/;";
console.log("Cookie deleted:", name);
}
// Example usage
deleteCookie("myCookie");
</script>
</body>
</html>
Output
<html>
<body>
<script>
function deleteCookie(name) {
// Get current IST time and convert it to UTC (IST is UTC + 5:30)
let date = new Date();
date.setTime(date.getTime() - (5.5 * 60 * 60 * 1000)); // Subtracting 5:30 to
get UTC time
let utcDate = new Date(date.getTime() - (24 * 60 * 60 * 1000)); // Set to 1
day ago in UTC
document.cookie = name + "=; expires=" + utcDate.toUTCString() + ";
path=/;";
console.log("Cookie deleted:", name);
}
// Example usage
deleteCookie("myCookie");
</script>
</body>
</html>
output
<!DOCTYPE html>
<html>
<body>
<script>
function deleteCookie(name) {
// Set Max-Age to 0 to delete the cookie
document.cookie = name + "=; Max-Age=0; path=/;";
console.log("Cookie deleted:", name);
}
// Example usage
deleteCookie("myCookie");
</script>
</body>
</html>
Max-Age=0: This attribute immediately expires the cookie, effectively
deleting it.
path=/: Ensures the cookie is deleted from the entire site, not just the
current page.
window object
The Window object in JavaScript represents a browser window or a
frame within a browser. It is the global object for all client-side JavaScript,
meaning that functions and properties related to the browser's window are part
of the Window object.
1. Opening a New Window:
We can use the window.open() method to open a new browser window or tab.
Syntax:
let newWindow = window.open(url, target, features);
url: The URL to load in the new window (e.g., "https://example.com").
target: The target for the new window ("_blank" for a new tab, "_self" to
replace the current page).
features: Optional. A comma-separated list of window features like
width=500,height=400.
example
let newWindow = window.open("https://example.com", "_blank", "width=500,height=400");
<!DOCTYPE html>
<html>
<head>
<title>window.open() Example</title>
</head>
<body>
<button onclick="openWindow()">Open New Window</button>
<script>
function openWindow() {
// Opens a new window
window.open("https://example.com", "_blank", "width=500,height=400");
}
</script>
</body>
</html>
Syntax:
newWindow.focus();
Example
<html>
<head>
<title>newWindow.focus() Example</title>
</head>
<body>
<button onclick="openAndFocus()">Open and Focus New Window</button>
<script>
let newWindow;
function openAndFocus() {
// Opens a new window
newWindow = window.open("https://example.com", "_blank",
"width=500,height=400");
Window Position:
We can set the position of the new window using moveTo() when opening it using
the left and top parameters, which specify the position relative to the top-left corner of the
screen.
Syntax:
window.moveTo(x, y)
Moves the window to a specified position on the screen.
Example:
newWindow.moveTo(200, 150);
<html>
<head>
<title>window.moveTo() Example</title>
</head>
<body>
<button onclick="openAndMove()">Open and Move New Window</button>
<script>
let newWindow;
function openAndMove() {
// Opens a new window
newWindow = window.open("https://example.com", "_blank",
"width=500,height=400");
<html>
<head>
<title>newWindow.document.write() Example</title>
</head>
<body>
<button onclick="openAndWrite()">Open and Write to New Window</button>
<script>
let newWindow;
function openAndWrite() {
// Opens a new window
newWindow = window.open("", "_blank", "width=500,height=400");
Closing window
we can close the window programmatically using the close() method. The window object
must still be accessible (i.e., it cannot be closed by a user manually).
<html>
<head>
<title>newWindow.close() Example</title>
</head>
<body>
<button onclick="openAndClose()">Open and Close New Window</button>
<script>
let newWindow;
function openAndClose() {
// Opens a new window
newWindow = window.open("https://example.com", "_blank",
"width=500,height=400");