CSS Unit 4
CSS Unit 4
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.
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.
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>
<!DOCTYPE html>
<html lang="en">
<body>
<script>
document.cookie = “name = ABC; max-age = 100000; 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
Opening a window
The open() method opens a new browser window, or a new tab, depending on your browser
settings and the parameter values.
<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>
<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>
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>
<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
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.