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();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000)); // 30 days
let expires = "expires=" + date.toUTCString();
document.cookie = "username=JohnDoe;" + expires + ";path=/;";
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";
Reading a Cookie in JavaScript
1. document.cookie retrieves all cookies as a single string, where
each cookie is separated by a semicolon (;).
2. split(';') method splits the string into an array of individual
cookies, making it easier to iterate through them.
<html>
<body>
Enter UserName<br>
<input type="text" id="nm" >
<br>
<br>
<input type="button" onclick="writeCookie()" value="writeCookie">
<br>
<br>
<input type="button" onclick="readCookie()" value="readCookie">
<br>
<script>
function writeCookie()
{
value=document.getElementById("nm").value;
cookie_str="username="+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>
//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
Deleting using max-age variable
If you want to delete a cookie using the Max-Age attribute in JavaScript, you
can specify the age of the cookie in seconds. Setting Max-Age to 0 will
immediately delete the cookie
<!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");
"https://example.com": The URL to be loaded in the new window."
_blank": Specifies that the URL will open in a new tab or window.
"width=500,height=400": The size of the new window (optional).
<!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>
2. Giving the New Window Focus:
After opening a new window, you can bring it into focus using the focus() method. This is
useful when you want the new window to be the active window.
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");
// Brings the new window into focus
newWindow.focus();
}
</script>
</body>
</html>
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");
// Moves the new window to a specific position
newWindow.moveTo(200, 150);
}
</script>
</body>
</html>
Changing content of window:
Once a new window is opened, we can change its content using the document.write() method.
This rewrites the content of the window with whatever you specify.
Syntax
newWindow.document.write(htmlContent);
newWindow.document.write("<h1>Hello, this is new content!</h1>");
<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");
// Modifies the content of the new window
newWindow.document.write("<h1>Hello, this is new content!</h1>");
}
</script>
</body>
</html>
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).
Syntax
newWindow.close():
This method closes the opened window.
Example: newWindow.close();
<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");
// Closes the new window after 3 seconds
setTimeout(function() {
newWindow.close();
}, 3000);
}
</script>
</body>
</html>
Scrolling a Web Page in JavaScript
We can scroll a web page vertically using the window.scrollTo() method or
window.scrollBy().
This works with the current window.
Syntax:
window.scrollTo(x-coord, y-coord);
x-coord: Horizontal position to scroll to (in pixels).
y-coord: Vertical position to scroll to (in pixels).
<html>
<head>
<title>Scroll Example</title>
</head>
<body>
<button onclick="scrollToBottom()">Scroll to Bottom</button>
<script>
function scrollToBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
</script>
</body>
</html>
In this case, x is set to 0 (no horizontal scroll) and y is set to document.body.scrollHeight,
which scrolls to the very bottom of the page.
Opening Multiple Windows at Once
We can open multiple windows using window.open(). This creates new browser windows.
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
<html>
<head>
<title>Open Multiple Windows</title>
</head>
<body>
<button onclick="openWindows()">Open Multiple Windows</button>
<script>
function openWindows() {
// Open two different URLs in two separate windows
window.open('https://example.com', '_blank', 'width=500,height=500');
window.open('https://example2.com', '_blank', 'width=400,height=400');
}
</script>
</body>
</html>
Here, two URLs are opened in new windows, with different sizes specified by
the windowFeatures parameter.
Creating a Web Page in a New Window
We can dynamically create content in a new window using window.open() and
document.write() in the new window's context
Syntax
window.open();
newWindow.document.write(HTMLString);
window.open(): Opens a blank window.
HTMLString: A string of HTML content that is written into the new window's document.
<html>
<head>
<title>Create New Window</title>
</head>
<body>
<button onclick="createNewWindow()">Create New Window</button>
<script>
function createNewWindow() {
// Open a blank window and add content dynamically
let newWindow = window.open('', '', 'width=600,height=400');
newWindow.document.write('<h1>Welcome</h1><p>This is a new window</p>');
}
</script>
</body>
</html>
Scrolling a Web Page Using window in JavaScript
The scrollTo() method scrolls the document to specified coordinates.
For the scrollTo() method to work, the document must be larger than the screen, and the
scrollbar must be visible.
Syntax:
window.scrollTo(x-coord, y-coord);
x-coord: Horizontal position to scroll to (in pixels).
y-coord: Vertical position to scroll to (in pixels).
Example 1:
<html>
<head>
<title>Scroll Example</title>
</head>
<body>
<button onclick="scrollToBottom()">Scroll to Bottom</button>
<script>
function scrollToBottom() {
// Scroll to the bottom of the document
window.scrollTo(0, document.body.scrollHeight);
}
</script>
</body>
</html>
Example2:
<html>
<head>
<title>Scroll Example</title>
<style>
body {
width: 1000px;
height: 1500px;
}
button {
position: fixed;
}
</style>
</head>
<body>
<button onclick="scrollToBottom()">Scroll to Bottom</button>
This is Line 1
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
This is Line 2
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
This is Line 3
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
This is Line 4
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
This is Line 5
<script>
function scrollToBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
</script>
</body>
</html>
Opening Multiple Windows at Once
Syntax:
window.open(URL, windowName, [windowFeatures]);
URL: The URL to load in the new window.
windowName: The name of the new window (use _blank for a new tab or window).
windowFeatures: Optional. A string specifying the window's properties like width
and height (e.g., 'width=500,height=500').
Example:
<html>
<head>
<title>Open Multiple Windows</title>
</head>
<body>
<button onclick="openWindows()">Open Multiple Windows</button>
<script>
function openWindows() {
// Open two different URLs in two separate windows
window.open('https://example.com', '_blank', 'width=500,height=500');
window.open('https://example2.com', '_blank', 'width=400,height=400');
}
</script>
</body>
</html>
Explanation: window.open() opens new browser windows. Here, two URLs are opened in
new windows, with different sizes specified by the windowFeatures parameter.
Creating a Web Page in a New Window
Syntax:
javascript
Copy code
window.open();
newWindow.document.write(HTMLString);
window.open(): Opens a blank window.
HTMLString: A string of HTML content that is written into the new window's
document.
Example:
html
Copy code
<html>
<head>
<title>Create New Window</title>
</head>
<body>
<button onclick="createNewWindow()">Create New Window</button>
<script>
function createNewWindow() {
// Open a blank window and add content dynamically
let newWindow = window.open('', '', 'width=600,height=400');
newWindow.document.write('<h1>Welcome</h1><p>This is a new window</p>');
}
</script>
</body>
</html>
Explanation: The window.open() opens a new blank window, and the document.write()
method inserts the HTML content (<h1>...</h1><p>...</p>) into that new window.
JavaScript in URL (Bookmarklet)
Syntax:
javascript
Copy code
javascript:code;
code: Any valid JavaScript code that will run when entered in the browser's address
bar.
Example:
<html>
<head>
<title>Bookmarklet Example</title>
</head>
<body>
<p>Type the following in the browser's URL bar:</p>
<p><code>javascript:alert('Hello from URL');</code></p>
</body>
</html>
Explanation: When you type the javascript: prefix in the browser's address bar followed by
JavaScript code, it will execute. In this case, it shows an alert with the message 'Hello from
URL'.
JavaScript Timers
The window object allows execution of code at specified time intervals.
These time intervals are called timing events.
The two key methods to use with JavaScript are:
1. setTimeout()
2. setTimeInterval()
setTimeout()
setTimeout() delays the execution of the function.
Syntax:
setTimeout(function, delay);
function: The function to execute after the delay.
delay: The delay in milliseconds before the function is executed.
Example:
html
Copy code
<html>
<head>
<title>Timeout Example</title>
</head>
<body>
<script>
setTimeout(function() {
// Shows an alert after 2 seconds (2000 milliseconds)
alert('This will run after 2 seconds');
}, 2000);
</script>
</body>
</html>
setInterval():
setInterval() repeatedly runs a function every specified number of milliseconds
Syntax
setInterval(function, interval);
function: The function to execute repeatedly.
interval: The interval time (in milliseconds) between function executions.
<html>
<head>
<title>Interval Example</title>
</head>
<body>
<script>
setInterval(function()
{
// Logs a message every second (1000 milliseconds)
console.log('This message repeats every second');
}, 1000);
</script>
</body>
</html>
Cancel or stop the timer
To cancel or stop a timer in JavaScript, you can use clearTimeout() for timers set by
setTimeout() and clearInterval() for timers set by setInterval().
1. clearTimeout()
To cancel timer in JavaScript, we can use clearTimeout() for timers set by setTimeout()
Syntax:
clearTimeout(timeoutID);
timeoutID: The identifier returned by setTimeout() that you want to cancel.
<html>
<head>
<title>Cancel setTimeout</title>
</head>
<body>
<button onclick="startTimer()">Start Timer</button>
<button onclick="stopTimer()">Cancel Timer</button>
<script>
let timeoutID;
function startTimer() {
timeoutID = setTimeout(function() {
alert('This will not run if canceled');
}, 5000); // 5 seconds delay
}
function stopTimer() {
clearTimeout(timeoutID); // Cancels the timeout
alert('Timer Canceled');
}
</script>
</body>
</html>
clearInterval()
To cancel or stop a timer in JavaScript, we can use clearInterval() for timers set by
setInterval().
Syntax:
clearTimeout(timeoutID);
timeoutID: The identifier returned by setTimeout() that you want to cancel.
<html>
<head>
<title>Stop setInterval</title>
</head>
<body>
<button onclick="startInterval()">Start Interval</button>
<button onclick="stopInterval()">Stop Interval</button>
<script>
let intervalID;
function startInterval() {
intervalID = setInterval(function() {
console.log('This message repeats every second');
}, 1000); // 1 second interval
}
function stopInterval() {
clearInterval(intervalID); // Stops the interval
alert('Interval Stopped');
}
</script>
</body>
</html>
JavaScript in URL:
The URL object in JavaScript provides a way to work with URLs by parsing them into their
components. It allows you to create, modify, and interact with URLs.
Syntax
new URL(url, [base]);
url: The absolute or relative URL string.
base (optional): If provided, it acts as the base URL for resolving relative URLs.
Properties of URL Object
href: The full URL.
protocol: The protocol scheme (e.g., http:, https:).
host: The hostname and port number (e.g., example.com:80).
hostname: The domain (e.g., example.com).
pathname: The path (e.g., /path/to/resource).
<html>
<head>
<title>URL Object Example</title>
</head>
<body>
<script>
// Create a new URL object
let url = new URL('https://example.com:8080/path/to/resource');
// Access and log the properties
console.log('href:', url.href); // Full URL'https://example.com:8080/path/to/resource'
console.log('protocol:', url.protocol); // Protocol: 'https:'
console.log('host:', url.host); // Host: 'example.com:8080'
console.log('hostname:', url.hostname); // Hostname: 'example.com'
console.log('pathname:', url.pathname); // Pathname: '/path/to/resource'
</script>
</body>
</html>
Output in the console:
href: 'https://example.com:8080/path/to/resource'
protocol: 'https:'
host: 'example.com:8080'
hostname: 'example.com'
pathname: '/path/to/resource'
Browser Location and History:
Location object in javascript helps in storing the information of current URL
of the window object.
location object is child object of window object.
Syntax:
window.location
or
location
1. Accessing Location (window.location):
The window.location object contains information about the current URL and provides
methods for manipulating it.
1.1 Current URL:
let currentURL = window.location.href;
console.log(currentURL); // Outputs the full URL of the page
1.2 Redirect to another URL:
window.location.href = "https://example.com";
1.3 Reload the current page:
window.location.reload();
1.4 Access different parts of the URL:
let protocol = window.location.protocol; // e.g., "https:"
let host = window.location.host; // e.g., "www.example.com"
let path = window.location.pathname; // e.g., "/path/to/page"
let queryString = window.location.search; // e.g., "?id=123"
2. Accessing Browser History (window.history):
The window.history object allows navigation through the user's session history.
2.1 Go back to the previous page:
window.history.back();
2.2 Go forward to the next page:
window.history.forward();
2.3 Go to a specific page in history:
window.history.go(-2); // Go back 2 pages in history
2.4 Length of history:
let historyLength = window.history.length;
console.log(historyLength); // Outputs the number of entries in the history stack
Example1
Create a back button on a page:
<html>
<head>
<script>
function goBack() {
window.history.back()
}
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
</body>
</html>
Example2
Create a forward button on a page:
<html>
<head>
<script>
function goForward() {
window.history.forward()
}
</script>
</head>
<body>
<input type="button" value="Forward" onclick="goForward()">
</body>
</html>
Exmaple3
Location and History Example
<html>
<body>
<h1>Location and History Example</h1>
<!-- Display current URL -->
<p id="currentUrl"></p>
<!-- Buttons for history navigation -->
<button onclick="goBack()">Go Back</button>
<button onclick="goForward()">Go Forward</button>
<!-- Button to reload the page -->
<button onclick="reloadPage()">Reload Page</button>
<!-- Button to change the URL -->
<button onclick="redirectTo()">Redirect to Example.com</button>
<script>
// Display the current URL
document.getElementById("currentUrl").textContent = "Current URL: " +
window.location.href;
// Go back to the previous page
function goBack() {
window.history.back();
}
// Go forward to the next page
function goForward() {
window.history.forward();
}
// Reload the current page
function reloadPage() {
window.location.reload();
}
// Redirect to another URL
function redirectTo() {
window.location.href = "https://example.com";
}
</script>
</body>
</html>
JavaScript Security
Javascript is designed as an open scripting language.
It has own security model but it is not designed protect website owner or data passed
between browser and server.
Security model is designed to protect user from malicious website and as result.
It enforces strict limit on what author page allowed to do. multiple way of protecting web
page
1) Hiding your source code
2) Disabling right click button
3) Concealing Email address
4) Hiding Javascript
1. Hiding your source code
JavaScript is inherently an open, client-side language, meaning that the code can easily be
viewed by anyone through the browser’s developer tools. While you can’t fully hide your
code, there are methods to make it harder for others to understand or reverse-engineer it.
2. Disabling Right Click Button
By disabling the right mouse button on web page , visitor can not access the view source
menu option from context menu.
<html>
<body oncontextmenu="return false;">
<h1>Right Click Disabled</h1>
<p>Right-click is disabled on this page.</p>
</body>
</html>
3. Concealing Email Address
To protect email addresses from bots or scraping, you can use various methods such as
obfuscating the email or using JavaScript to display it dynamically.
<html>
<body>
<p id="email"></p>
<script>
// Build the email address dynamically
var user = "john.doe";
var domain = "example";
var tld = "com";
var email = user + "@" + domain + "." + tld;
document.getElementById("email").textContent = email;
</script>
</body>
</html>
4. Hiding JavaScript
While it's impossible to fully hide JavaScript from users, you can make it harder to access
or understand by minifying or obfuscating the code. This helps protect your logic, but
skilled users can still reverse-engineer the code.
function add(a, b) {
return a + b;
}
function _0x4f8b(_0x1a2d,_0x3469){return _0x1a2d+_0x3469;}
Another way,
Hiding JavaScript from a visitor by storing it in external file on your web server.
The external file should have .js extension. The browser then call the external file
whenever browser encounters JavaScript element.
If we look source code, you will reference external .js file but you wont see source code
of javascript.