0% found this document useful (0 votes)
2 views

CSS Unit 4

This document provides an overview of cookies and browser data management in JavaScript. It explains how cookies work, their elements, and how to create, read, and delete them, along with managing browser windows and their properties. Additionally, it covers methods for scrolling web pages and handling multiple windows in a browser environment.

Uploaded by

Pallavi Deokar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CSS Unit 4

This document provides an overview of cookies and browser data management in JavaScript. It explains how cookies work, their elements, and how to create, read, and delete them, along with managing browser windows and their properties. Additionally, it covers methods for scrolling web pages and handling multiple windows in a browser environment.

Uploaded by

Pallavi Deokar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Contents

Unit 4. Cookies and Browser Data ............................................................................................ 2


Cookies .................................................................................................................................. 2
How do cookies work?....................................................................................................... 2
Cookie Elements ................................................................................................................ 2
Creating a cookie with additional attributes: ..................................................................... 3
Reading a Cookie ............................................................................................................... 3
Deleting a cookie ............................................................................................................... 5
Browser Data ......................................................................................................................... 6
Properties of Window Object............................................................................................. 6
Opening a window ............................................................................................................. 6
Giving the new window focus ........................................................................................... 7
Creating a Cookie .............................................................................................................. 7
Changing the window position .......................................................................................... 8
Changing the content of a window .................................................................................... 8
Closing a window .............................................................................................................. 9
Scrolling a web page ........................................................................................................ 10
Multiple windows at once ................................................................................................ 12
Creating a web page in new window ............................................................................... 13
JavaScript in URLs .......................................................................................................... 13
JavaScript Security........................................................................................................... 14
Timers .............................................................................................................................. 15
Unit 4. Cookies and Browser Data
Cookies

A JS cookie is a small piece of data that a website stores on a user’s computer through their
web browser. Cookies help websites remember information about the user for future visits.
How do cookies work?
1. Storage: When the user visits a website, it can create a cookie to store information like
login status, preferences, or items in the shopping cart.
2. Data Format: Cookies typically consist of a name – value pair, and they can also have
additional attributes like expiration dates or paths.
3. Expiration: Cookies can be set to expire after a certain period. Some cookies last only
while you are on the website (session cookies), while others can stay for days, months
or even years (persistent cookies).
4. Access: The next time the user visits the website, the browser sends the cookie back to
the server. This allows the site to “remember” the user and provide a more personalized
experience.
5. Privacy: While cookies enhance user experience, they can also raise privacy concerns
because they can track user behaviour across different sites.
Cookie Elements
A cookie consists of plain – text data record of the following variable length fields:
 Name=value: Cookies are set and retrieved in the form of key – value pairs.
 Domain: It is the domain name of the site that can access the cookie.
 Path: It is 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.
 Expires: It specifies the date and time when the cookie expires. If not set, the cookie
expires when the browser is closed.
 Max-Age: Defines the lifetime of the cookie in seconds from the time it is set.
If both Expires and Max-Age are specified, then Max-Age takes precedence. This attribute is more flexible than
expires, as it is relative to the current time.

 Secure: It indicates that the cookie should be transmitted over secure (https)
connections.
 HttpOnly: When this attribute is set, the cookie is inaccessible to JS, i.e., it cannot be
accessed or modified using ‘document.cookie’ and is only used for server – side
communication.
 SameSite: It controls whether the cookie is sent along with the cross site requests. The
possible values for this attribute are:
o lax (default): Cookies are not sent on cross – site requests, but are sent when
navigating to the cookie’s origin site.
o strict: Cookies are only sent on same – site requests.
o none: Cookies are sent on both same – site and cross – site requests. This value
requires the ‘secure’ attribute to be set if used.

How to view cookies in a Web Browser:


Right – click on the web page → Inspect → >> → Application → Cookies → Click on the url below cookies → You
will get all the cookies present for that web page on the RHS.
Creating a cookie with additional attributes:

Example:
<!DOCTYPE html>
<html>
<head>
<script>
let exp = new Date();
exp.setTime(exp.getTime() + (7*24*60*60*1000)); //7 days
let expires = "expires = "+exp.toUTCString();
document.cookie = "username=abc;"+expires+";Secure;SameSite=None;path=/";
alert(document.cokie);
</script>
</head>
</html>

Reading a Cookie

Reading a JS cookie involves accessing the document.cookie property. However, cookies are
stored as a single string with all the cookies concatenated together, separated by semicolons.
Each cookie is a key – value pair (name = value). So you need to parse the string to extract the
specific cookie you want.

Example: document.cookie = “username = abc”;


The above example creates a cookie named “username” with the value “abc”.

Steps to read a JS Cookie:

1. Access ‘document.cookie’: This gives you a string containing all the cookies in the
format ‘name1 = value1; name2 = value2;…’.
2. Split the cookies: Since the cookies are separated by the semicolons, split the
‘document.cookie’ string into an array of individual cookies.
3. Find the desired cookie: Loop through the array to find the cookie by its name.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create Cookies and View Cookies</title>
</head>
<body>
<script>
function getCookie(name)
{
let cookies = document.cookie; //get all cookies in a single string
let arr = cookies.split(';'); //split all the cookies into an array
for(let i = 0; i < arr.length; i++) //loop through the cookies to find one with a matching name
{
let cookie = arr[i].trim(); //remove white spaces if any
if(cookie.indexOf(name+"=")===0) //check if the names match
return cookie.substring(name.length + 1); //return the cookie name
}
return null; //if the cookie is not found
}
document.cookie = "name=ABC; max-age=" + (7 * 24 * 60 * 60) + "; path=/; SameSite=Lax";
let val = getCookie("name"); //get the value of the name cookie
if(val)
alert("Cookie:" +val);
else
alert("Cookie not found");
</script>
</body>
</html>

Setting the expiration date of a cookie


In JS, the expiration date of a cookie can be set using
 the ‘expires’ attribute
 the ‘max-age’ attribute
1. Using the ‘expires’ attribute
The ‘expires’ attribute allows to specify an exact expiration date and time for the cookie in
UTC format. If no expiration date is set, the cookie becomes a session cookie and is deleted
when the browser is closed.
The value for the ‘expires’ attribute should be a date string formatted as:
Day, DD Mon YYYY HH:MM:SS UTC

<!DOCTYPE html>
<html lang="en">
<body>
<script>
document.cookie = “name = ABC; max-age = 100000; path = /; SameSite = Lax”;
</script>
</body>
</html>

2. Using the ‘max-age’ attribute


The ‘max-age’ attribute specifies the cookie’s lifespan in seconds from the time it is set. This
is a more modern alternative to ‘expires’ and can be easier to use for relative times.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
document.cookie = “name = ABC; expires = Thu, 31 Oct 2024 22:07:56 UTC; path = /; SameSite = Lax”;
</script>
</body>
</html>

Deleting a cookie
To delete a JS Cookie, you need to set its expiration date to a time in the past. This tells the
browser that the cookie is no longer valid, prompting it to remove the cookie.
Steps to delete a cookie:
Step 1: Set the same name – You must specify the same name for the cookie you want to delete.
Step 2: Set the expiration date – Set the ‘expires’ attribute to a date in the past.
Step 3: Include other attributes: If you originally set the cookie with additional attributes (like
path or domain), you should include those as well when deleting a cookie.
Note:
If the cookie was set with a specific domain, path or secure attribute, you must specify those attributes when deleting
the cookie for the deletion to be effective.
If you do not know the exact path or other attributes used when deleting the cookie, the deletion may not be successful.

Browser Data

Properties of Window Object


1) status – The contents of the status bar (at the bottom of the browser window).
Example: window.status = “Hello World!”;
2) location – The location and the url of the document currently loaded into the window
(as displayed in the location bar).
Example: alert(window.loaction);

Opening a window
The open() method opens a new browser window, or a new tab, depending on your browser
settings and the parameter values.

Syntax: window.open(url, name, specs, replace);


Where,
1) url – The url of the page to be opened. If no url is specified, a new blank window/tab is
opened.
2) name – The target attribute or the name of the window. Following values are supported:
a. _blank: New window/tab
b. _parent: Parent frame
c. _self: Replace current page
d. _top: Any framesets loaded are replaced
e. name: Name of the window
3) specs – A comma separated list of items, no white spaces. Following values are
supported:
a. fullscreen = yes/no/1/0: Whether or not to display the browser in full screen
mode. Default is no. A window in full screen mode must also be in theatre mode.
b. location: whether or not to display the address field.
c. menubar: whether or not to display the menu bar.
d. resizable: whether or not window is resizable.
e. scrollbars: whether or not to display the scroll bars.
f. titlebar: whether or not to display the title bar.
g. toolbar: whether or not to display the toolbar.
h. top = pixels: the top position of the window. Negative values are not allowed.
i. left: the left position of the window. Negative values are not allowed.
j. height: height of the window. Minimum value is hundred.
k. width: width of the window. Minimum value is hundred.
4) replace – It specifies whether the URL creates a new entry in the history list. Possible
values are true or false.

<html>
<body>
<p>Click the button to open an about:blank page in a new browser window that is 200px wide and 100px tall.</p>
<form>
<button onclick="myFunction()">Open Window</button>
</form>
<script>
function myFunction() {
var myWindow = window.open("", "", "width=200,height=100");
}
</script>
</body>
</html>

Giving the new window focus


The focus() method sets focus to the current window. The blur() method removes focus from
the current window.

<html>
<body>
<form>
<button onclick="myFunction()">Open Window</button>
</form>
<script>
function myFunction()
{
Creating
var myWindow a Cookie
= window.open("", "", "width=200,height=100");
} To create a cookie, we can simply assign a string to ‘document.cookie’. This string contains
the cookie name, value and optionally, other attributes like date, path, domain, etc.
</script>
Syntax: document.cookie = “name = value”;
</body>
</html>
Changing the window position
When we create a window, we can set a specific position to the new window. The attributes
‘left’ and ‘top’ are used to specify the position of the new window. The volumes to these
attributes are passed in open() as parameters.

<html>
<body>
<p>Click the button to open an about:blank page in a new browser window that is
200px wide and 100px tall.</p>
<form>
<button onclick="myFunction()">Open Window</button>
</form>
<script>
function myFunction() {
var myWindow = window.open("", "", "width=200,height=100");
}
</script>
</body>
</html>

Changing the content of a window


The contents of a window can be changed dynamically in the following ways –
- Changing the content of the whole window
- Changing the content of a specific element
<html><body>
<h3>Welcome to the <span id="s1"> JavaScript </span> Programming!!!</h3>
<form>
<button onclick="whole()">Change Whole Content</button>
<button onclick="specific()">Change Specific Content</button>
</form><script>
function whole() {
document.write("<h3>Whole content is changed after clicked on change whole content </h3>");
}
function specific() {
document.getElementById("s1").innerHTML = "Client Side Scripting Language";
}
</script></body></html>
<html>
<body>
<p>Click the below button to change the content of window</p>
<form>
<button onclick="content()">Change Content</button>
</form>
<script>
function content() {
window.open("https://www.google.com","_self");
}
</script>
</body>
</html>

Closing a window
The window.close() method closes the current window, or the window on which it was called.
This method can only be called on a window that was opened by a script using window.open(),
or on top level windows that have a single history entry. If the window doesn’t match these
requirements, an error similar to this one appears in the console: “script may not close windows
that were not opened by script.”
Syntax: window.close();

<html>
<body>
<h3>The open() and close() Method</h3>
<form>
<button onclick="openWin()">Open Window</button>
<button onclick="closeWin()">Close Window</button>
</form>
<script>
let myWindow;
function openWin() {
myWindow = window.open("", "_blank");
}
function closeWin() {
myWindow.close();
}
</script>
</body>
</html>
Scrolling a web page
The contents of the document window can be scrolled to the specified horizontal and vertical
positions using-
- scrollTo()
- scrollBy()
scrollTo() – It scrolls the document to the specified coordinates.
Syntax: window.scrollTo(x, y);
OR
scrollTo(x, y);
where,
x, y: The coordinate to scroll to, horizontally and vertically respectively, in pixels.

<html>
<head>
<style>
body{
width:5000px;
height:5000px;
}
</style>
</head>
<body>
<button onclick="myFunction()" style="position:fixed">ScrollTo</button>
<script>
function myFunction(){
window.scrollTo(1500, 1500);
}
</script>
</body>
</html>

scrollBy() – The scrollBy() method scrolls the document by the specified number of pixels.
Syntax: window.scrollBy(x, y);
OR
scrollBy(x, y);
Where,
x, y: The Number of pixels to scroll horizontally and vertically respectively. Positive values
scroll to the right, negative values to the left.

<html>
<head>
<style>
body
{
width:5000px;
height:5000px;
}
button
{
position:fixed;
font-size: 20px;
}
</style>
</head>
<body>
<form>
<button onclick="left()" > Left </button><br><br>
<button onclick="right()" > Right</button><br><br>
<button onclick="up()" > Up </button><br><br>
<button onclick="down()" > Down </button>
</form>
<script>
function left()
{
window.scrollBy(-30, 0);
}
function right()
{
window.scrollBy(30, 0);
}
function up()
{
window.scrollBy(0, -30);
}
function down()
{
window.scrollBy(0, 30);
}
</script>
</body>
</html>

Multiple windows at once


window.open() function of JavaScript can be used multiple times to open multiple
windows/tabs. We can also use for loop to open multiple windows. The last opened window
will get focus by default.
<html>
<head>
<script>
function open_Twowin() {
window.open("http://www.google.com/")
window.open("http://www.yahoo.com/") }
function open_Fourwin() {
for(var i=0;i<4;i++)
window.open("","","height=200,width=300"); }
</script></head>
<body>
<form>
<input type=button value="Open Two Windows" onclick="open_Twowin()">
<input type=button value="Open Four Windows" onclick="open_Fourwin()">
</form>
</body>
</html>
Creating a web page in new window
We can write content to newly created windows once they are created either using the standard
document.write() method or potentially even manipulate the window with DOM methods. The
HTML code as string parameter passed to the write function.

<html>
<head>
<script>
function myFunction() {
var myWindow = window.open("", "", "left=400,top=50,width=300,height=300");
myWindow.document.write("<html>");
myWindow.document.write("<head>");
myWindow.document.write("<title>Create webpage in new window</title>");
myWindow.document.write("</head>");
myWindow.document.write("<body>");
myWindow.document.write("<h2>Welcome</h2>");
myWindow.document.write("<h3>I am Newly Created webpage in new window</h3>");
myWindow.document.write("</body>");
myWindow.document.write("</html>");
}
</script>
</head>
<body>
<form>
<button onclick="myFunction()">Create Webpage in new window</button>
</body>
<form>
</body>
</html>

JavaScript in URLs
 JavaScript code can be included on the client side is in a URL following the javascript:
pseudo-protocol specifier.
 This special protocol type specifies that the body of the URL is arbitrary JavaScript
code to be interpreted by the JavaScript interpreter.
 If the JavaScript code in a javascript: URL contains multiple statements, the statements
must be separated from one another by semicolons. Such a URL might look like the
following: javascript:var now = new Date(); "The time is:" + now;
 When the browser "loads" one of these JavaScript URLs, it executes the JavaScript
code contained in the URL and displays the "document" referred to by the URL.
 This "document" is the string value of the last JavaScript statement in the URL.
 This string will be formatted and displayed just like any other document loaded into the
browser.
 More commonly, a JavaScript URL will contain JavaScript statements that perform
actions but return no value. For example: javascript:alert("Hello World!") When this
sort of URL is "loaded," the browser executes the JavaScript code, but, because there
is no value to display as the new document, it does not modify the currently displayed
document.
<html>
<body>
<form>
<button onclick="myFunction()">Open</button>
<script>
function myFunction()
{
var myWindow = window.open("javascript:alert('Hello...This code is written in url')", "", "left=400, top=50,
width=300, height=300");
}
</script>
</form>
</body>
</html>

JavaScript Security

 JavaScript applications are especially vulnerable to attack because the application’s


code is accessible to the user.
 This makes it much easier for an attacker to identify and exploit vulnerabilities in a
front-end application. Also, an attacker has the ability to modify the code in their
browser or send requests directly to the server-side applications, bypassing front-end
protections.
 There are two measures that can be taken to contain this JavaScript security risk.
 First is sandboxing, or running scripts separately so that they can only access certain
resources and perform specific tasks.
 The second measure is implementing the same origin policy, which prevents scripts
from one site from accessing data that is used by scripts from other sites.
 Many JavaScript security vulnerabilities are the result of browser authors failing to take
these measures to contain DOM-based JavaScript security risks.
JavaScript security vulnerabilities:

 Cross-Site Scripting (XSS):


A type of client-side code injection attack, in which a hacker embeds malicious code on the
client side or front end of a web application. The code then launches when the victim loads the
website. The malicious code may capture sensitive information when the user enters data into
a form or steal cookies to impersonate the user for social engineering purposes.
 Cross-Site Request Forgery:
In a CSRF attack, the attacker tricks a user’s browser into performing requests to a website that
they have already authenticated to. This could allow an attacker to change the user’s password
on the site, perform a bank transaction, make social media posts, or take other undesirable
actions.

Timers
 In JavaScript, a timer is created to execute a task or any function at a particular time.
 Basically, the timer is used to delay the execution of the program or to execute the
JavaScript code in a regular time interval.
 With the help of timer, we can delay the execution of the code. So, the code does not
complete it's execution at the same time when an event triggers or page loads.
 The best example of the timer is advertisement banners on websites, which change after
every 2-3 seconds.
 JavaScript offers two timer functions, which helps to delay in execution of code and
also allows to perform one or more operations repeatedly.
1) setInterval()
2) setTimeout()
1) setInterval()
 The setInterval() method calls a function at specified intervals (in milliseconds).
 The setInterval() method continues calling the function until clearInterval() is called, or
the window is closed.
 Syntax:
setInterval(function, milliseconds)
Where,
- function(Required): The function to execute.
- milliseconds (Optional): Number of milliseconds to wait before executing. Default
value is 0.
- Return type: A number, the id of the timer. Use this id with clearTimeout(id) to cancel
the timer.
How to Stop the Execution?
 The clearTimeout() method stops the execution of the function specified in setTimeout().
 window.clearTimeout(timeoutVariable) The window.clearTimeout() method can be written without the
window prefix.
 The clearTimeout() method uses the variable returned from setTimeout():
myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);

<!DOCTYPE html>
<html>
<body>
<h2>The setTimeout() Method</h2>
<p>Wait 5 seconds for the message after clicking the submit button:</p>
<p>If you don't want the message, click "Don't display message" before 5 seconds after clicking the submit
button:</p>
<form name="form1">
Enter your name: <input type="text" onchange="msg1()"><br><br>
<input type="button" value="Submit" onclick="msg1()">
<input type="button" value="Don't display message" onclick="noMSG()">
</form>
<h2 id="demo"></h2>
<script>
let myTimeout;
function msg() {
document.getElementById("demo").innerHTML = "Welcome to the JavaScript Programming...";
}
function msg1() {
myTimeout = setTimeout(msg, 5000); // Wait for 5 seconds (5000 ms)
}
function noMSG() {
clearTimeout(myTimeout); // Cancels the timeout
document.getElementById("demo").innerHTML = "Message Blocked...";
}
</script>
</body>
</html>
Note:
After clicked on submit button message will be displayed only once after 5 seconds using setTimeout() function.
If we don’t want to show message then message is blocked using clearTimeout() function.

You might also like