0% found this document useful (0 votes)
11 views18 pages

Unit 4 - 45256988 - 2024 - 10 - 24 - 08 - 54

Cookies are small text files stored on devices that enhance the browsing experience by remembering user preferences and enabling personalized content. They can be categorized into session cookies, which are temporary, and persistent cookies, which remain until a set expiration date. The document also explains how to create, read, and delete cookies using JavaScript, along with examples of managing cookie values.

Uploaded by

giteanuja09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views18 pages

Unit 4 - 45256988 - 2024 - 10 - 24 - 08 - 54

Cookies are small text files stored on devices that enhance the browsing experience by remembering user preferences and enabling personalized content. They can be categorized into session cookies, which are temporary, and persistent cookies, which remain until a set expiration date. The document also explains how to create, read, and delete cookies using JavaScript, along with examples of managing cookie values.

Uploaded by

giteanuja09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Cookies:

A cookie is a small text file that a web site saves on your PC, mobile phone or other device,
containing information about your browsing on that site.
Cookies are necessary to facilitate browsing and make it more convenient; they do not harm
your computer.

Why are cookies used on this website?


Cookies are an essential part of how our website operates.
The main purpose of our cookies is to improve your browsing experience.
For example, to remember your preferences (language, country, etc.) during browsing and on
future visits.
The information collected in cookies also enables us to improve our website, for example, by
estimating user numbers and ways users use the site, adapting the site to individual user's
interests, speeding up searches, etc.
Sometimes, if we have obtained your consent(permission), we can use cookies, tags or other
similar instruments to obtain information that enables us to show you advertising based on your
navigation habits on our own web site, those of other suppliers or in other ways.

Basics of Cookies
 Cookies is a small piece of data stored in a file on your computer.
 The information present in the cookies is accessed by the web browser.
A cookie contains the information as a string generally in the form of a name-value pair
separated by semi-colons.
 It maintains the state of a user and remembers the user's information among all the
web pages.
 Cookie is a small text file which contains following data:
- A name-value pair containing the actual data
- An expiry date after which it is no longer valid
- The domain and path of the server

Cookies are a plain text data record of 5 variable-length fields –


Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor
quits the browser.
Domain − The domain name of your site.
Path − 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.
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a
secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key-value pairs

Client Side Scripting (Unit 4) Arrow Computer Academy


 How Cookies Works?
o When a user sends a request to the server, then each of that request is treated as a new request
sent by the different user.
o So, to recognize the old user, we need to add the cookie with the response from the server to
browser at the client-side.
o Now, whenever a user sends a request to the server, the cookie is added with that request
automatically. Due to the cookie, the server recognizes the users.

Cookies remembers the information about the user in the following ways -
Step 1: When the user visits the web page his/her name can be stored in a cookie
Step 2: Next time when the user visits the page, the cookie remembers his/her name.

There are two types of cookies: Session cookies and persistent cookies
Session Cookies : Session cookies is a cookie that remains in temporary memory only
while user is reading and navigating the web site. The cookie is automatically deleted
when the user exits the browser application.

Persistent Cookies : A persistent cookie is a cookie that is assigned an expiration date. A


persistent cookie is written to the computer's hard disk and remains there until the
expiration date has been reached; then it is deleted.

Q] Describe, how to read cookie value and write a cookie value. Explain with
example. [W-19][6 M]

Creating Cookies
JavaScript can create, read or delete a cookie using document.cookie property
The simplest way to create a cookie is to assign a string value to the document.cookie object,
which looks like this.
document.cookie = " key1 = value1; key2 = value2; expires = date";
document.cookie = "username=Arrow";

Here the expires attribute is optional.


If you provide this attribute with a valid date or time, then the cookie will expire on a given date
or time and thereafter, the cookies' value will not be accessible.
Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you
may want to use the JavaScript escape() function to encode the value before storing it in the
cookie. If you do this, you will also have to use the corresponding unescape() function when you
read the cookie value.

Client Side Scripting (Unit 4) Arrow Computer Academy


Example Write a JavaScript for creating a cookie for the user name.

<html>
<head>

<script type = "text/javascript">


function WriteCookie()
{
if( document.myform.customer.value == "" )
{
alert("Enter some value!");
return;
}

cookievalue = escape(document.myform.customer.value) + ";";


document.cookie="name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()">
</form>
</body>
</html>

Now your machine has a cookie called name. You can set multiple cookies using multiple key =
value pairs separated by comma.

 Creating Multiple Cookies


<html>
<head>
<script type = "text/javascript">
function WriteCookie()
{
cookievalue = escape(document.myform.Fname.value) + ";";
document.cookie="Fname=" + cookievalue;
cookievalue = escape(document.myform.Lname.value) + ";";
document.cookie="Lname=" + cookievalue;
cookievalue=document.myform.Gender.value +";" ;
document.cookie="Gender=" + cookievalue;
document.write ("Setting Cookies ");
}
</script>

Client Side Scripting (Unit 4) Arrow Computer Academy


</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "Fname"/><br>
Enter name: <input type = "text" name = "Lname"/><br>
<input type="radio" name="Gender" value="Male" checked>Male
<input type="radio" name="Gender" value="Female">Female<br>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()">
</form>
</body>
</html>

 Reading a Cookie Value

It is a common practice to create a cookie and then read the value of the created cookie.
The document.cookie string will keep a list of NAME=VALUE pairs separated by semicolons,
name is the name of a cookie and value is its string value.
Using the split() function the string of cookies is break into key and values.
The split() method finds the = character in the cookie, and then take all the characters to the left of
the = and store them into array [0].
Next the split() method takes all the characters from the right of the = up to semicolon ( ; ) but not
Including the semicolon, and assign those characters to array[1]
Thus we can obtain the name value pair in array[0] and array[1] respectively.

Following example illustrates how to read the cookies value.

allcookies = “Academy = Arrow ; Branch = Computer ; Subject = CSS “


cookiearray
0 1 2
Academy = Arrow Branch = Computer Subject = CSS

name= Subject
value = CSS

<html>
<head>
<script type = "text/javascript">
function ReadCookie()
{
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies +”<br>”);

// Get all the cookies pairs in an array


cookiearray = allcookies.split(';');

// Now take key value pair out of this array

Client Side Scripting (Unit 4) Arrow Computer Academy


for(var i=0; i<cookiearray.length; i++)
{
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
</script>
</head>

<body>
<form name = "myform" action = "">
<p> click the following button and see the result:</p>
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form>
</body>
</html>

Note − There may be some other cookies already set on your machine. The above code will display
all the cookies set on your machine.

Setting Cookies Expiry Date


You can extend the life of a cookie beyond the current browser session by setting an expiration
date and saving the expiry date within the cookie. This can be done by setting
the ‘expires’ attribute to a date and time.
Example
Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.
<html>
<head>
<script type = "text/javascript">

function WriteCookie() {

var now = new Date();


now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"

document.cookie = "name=" + cookievalue + "expires=" + now.toUTCString() + ";"


document.write ("Setting Cookies : " + "name=" + cookievalue );
}

</script>
</head>
<body>
<form name = "myform" action = "">

Client Side Scripting (Unit 4) Arrow Computer Academy


Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>

Deleting a Cookie
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return
nothing. To do this, you just need to set the expiry date to a time in the past.
Example
Try the following example. It illustrates how to delete a cookie by setting its expiry date to one
month behind the current date.
<html>
<head>
<script type = "text/javascript">

function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"

document.cookie = "name=" + cookievalue + "expires=" + now.toUTCString() + ";"


document.write ("Setting Cookies : " + "name=" + cookievalue );
}

</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>

Client Side Scripting (Unit 4) Arrow Computer Academy


4.2 Browser
Opening a Window
It is possible to open a new browser window from a currently running JavaScript .
For that purpose the window object is used.
This window object has various useful properties and methods.
The window.open() method is used to open a new browser window or a new tab depending
on the browser setting and the parameter values.
Syntax
window.open(URL,name,style)
URL Optional. Specifies the URL of the page to open. If no URL is specified, a new
window/tab with about:blank is opened

name Optional. Specifies the target attribute or the name of the window. The following
values are supported:
 _blank - URL is loaded into a new window, or tab. This is default
 _self - URL replaces the current page
 _parent - URL is loaded into the parent frame
 _top- URL replaces any framesets that may be loaded. ( A collection of frames in
the browser window is known as a frameset.)

style Optional. A comma-separated list of items, no whitespaces. The following values are
supported:
fullscreen=yes|no|1|0 Whether or not to display the browser in full-screen
mode. Default is no.

height=pixels The height of the window. Min. value is 100

left=pixels The left position of the window. Negative values not


allowed

menubar=yes|no|1|0 Whether or not to display the menu bar

resizable=yes|no|1|0 Whether or not the window is resizable.

scrollbars=yes|no|1|0 Whether or not to display scroll bars. IE, Firefox &


Opera only

status=yes|no|1|0 Whether or not to add a status bar

titlebar=yes|no|1|0 Whether or not to display the title bar.

toolbar=yes|no|1|0 Whether or not to display the browser toolbar.

top=pixels The top position of the window. Negative values not


allowed

width=pixels The width of the window. Min. value is 100

Client Side Scripting (Unit 4) Arrow Computer Academy


Example 1: Open an about:blank page in a new window/tab

<!DOCTYPE html>
<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>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var myWindow = window.open("", "", "width=200,height=100");
}
</script>
</body>
</html>

Window Position
We can set the desired position for the window.
Using the left and top attribute values the window position can be set.
Example : left and top attribute

<!DOCTYPE html>
<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>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var myWindow = window.open("", "", "width=200,height=100,top=100,left=300");
}
</script>
</body>
</html>

Client Side Scripting (Unit 4) Arrow Computer Academy


Example : Replace the current window with a new window:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to put the new window in the current window.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var myWindow = window.open("", "_self");
myWindow.document.write("<p>I replaced the current window.</p>");
}
</script>

</body>
</html>

Example 4: Open Specified URL

<!DOCTYPE html>
<html>
<body>
<p>Click the button to open a new browser window.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
window.open("https://arrowcomputeracademy.business.site/");
}
</script>
</body>
</html>

4.2.4 Changing the content of window


By writing some text to the newly created window we can change content of window

<html>
<body>
<p>Click the button to open a new tab </p>
<button onclick="NewTab()">Open Window</button>
<script>
function NewTab() {
var mywin=window.open("","","width=200,height=200")
mywin.document.write("<p>This line is written in current window</p>")

Client Side Scripting (Unit 4) Arrow Computer Academy


}
</script>
</body>
</html>

4.2.5 Closing a Window

The most simple operation about the window is to close it. It can be closed using the function
close()

<!DOCTYPE html>
<html>
<body>

<button onclick="openWin()">Open myWindow</button>


<button onclick="closeWin()">Close myWindow</button>

<script>
var myWindow;

function openWin() {
myWindow = window.open("", "", "width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}

function closeWin() {
myWindow.close();
}
</script>

</body>
</html>

4.2.6 Multiple Window at a Glance


 It is possible to open up multiple windows at a time.
 It is simple to open multiple windows. Using Open() method in a loop.

Example
<html>
<body>
<p>Click the button to open a new tab </p>
<button onclick="NewTab()">Open Window</button>
<script>
function NewTab()
{
for(i=0;i<5;i++)

Client Side Scripting (Unit 4) Arrow Computer Academy


{
var mywin=window.open("","","width=100,height=100")
}
}
</script>
</body>
</html>

Timing Events / Timers


The window object allows execution of code at specified time intervals.
These time intervals are called timing events.
The setTimeout() Method :-
window.setTimeout(function, milliseconds);
The window.setTimeout() method can be written without the window prefix.
The first parameter is a function to be executed.
The second parameter indicates the number of milliseconds before execution.
Example
Click a button. Wait 3 seconds, and the page will alert "Hello":
<!DOCTYPE html>
<html>
<body>

<p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>
<button onclick="setTimeout(myFunction, 3000);">Try it</button>
<script>
function myFunction()
{
alert('Hello');
}
</script>
</body>
</html>

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);

Client Side Scripting (Unit 4) Arrow Computer Academy


If the function has not already been executed, you can stop the execution by calling the
clearTimeout() method:

Example:
<!DOCTYPE html>
<html>
<body>

<p>Click "Try it". Wait 3 seconds. The page will alert "Hello".</p>
<p>Click "Stop" to prevent the first function to execute.</p>
<p>(You must click "Stop" before the 3 seconds are up.)</p>

<button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button>


<button onclick="clearTimeout(myVar)">Stop it</button>

<script>
function myFunction()
{
alert("Hello");
}
</script>
</body>
</html>

scrollTo()
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, y)
or
scrollTo(x, y)
Parameters
x Required. The coordinate to scroll to (horizontally), in pixels.
y Required. The coordinate to scroll to (vertically), in pixels.
Return Value NONE

<html>
<head>
<script type = "text/javascript">
function scrollwindow()
{
window.scrollTo(0,200);
}

Client Side Scripting (Unit 4) Arrow Computer Academy


</script>
</head>
<body>
<p>click to scroll</p>
<input type="button" value="Scroll Window" onclick="scrollwindow()">
<p>A</p>

<br><br><br><br><br><br>

<p>B</p>

<br><br><br><br><br><br>

<p>C</p>

<br><br><br><br><br><br>

<p>D</p>

<br><br><br><br><br><br>

<p>E</p>

<br><br><br><br><br><br><br><br>

<P>-------------Window Scrolled</p>
</body>
</html>

BROWSER LOCATION AND HISTORY

1. window.location.pathname :
Gives complete path at which the web page is located.
2. window.location.hostname:
Gives name of host on which the webpage is running. It gives domain name
3. window.location.protocol:
Gives the protocol used for the webpage. Such as HTTP, HTTPS

Q Write a JavaScript code to get a pathname.

<html>
<head>
<script type="text/javascript">
function display()
{

Client Side Scripting (Unit 4) Arrow Computer Academy


document.getElementById("ID").innerHTML = "This web page is at path:" +
window.location.pathname;
}
</script>
</head>
<body>
<input type="button" value="GetPath" onclick="display()">
<p id="ID"></p>
</body>
</html>

Q Write a JavaScript code to get the protocol.


<html>
<head>
<script type="text/javascript">
function display()
{
document.getElementById("ID").innerHTML = "The protocol of Web Page is:" +
window.location.protocol;
}
</script>
</head>
<body>
<p>Click the button to get the Protocol</p>
<input type="button" value="GetProtocol" onclick="display()">
<p id="ID"></p>
</body>
</html>

Q Write a JavaScript code to get the hostname of webpage.

<html>
<head>
<script type="text/javascript">
function display()
{
document.getElementById("ID").innerHTML = "The hostname of Web Page is:" +
window.location.hostname;
}
</script>
</head>
<body>
<input type="button" value="GetHost" onclick="display()">
<p id="ID"></p>
</body>
</html>

Client Side Scripting (Unit 4) Arrow Computer Academy


Window History
The window.history object can be written without the window prefix.
To protect the privacy of the users, there are limitations to how JavaScript can access this object.
Some methods:
 history.back() - same as clicking back in the browser
 history.forward() - same as clicking forward in the browser

<html>
<head>
<script type="text/javascript">
function previous()
{
window.history.back();
}
function next()
{
window.history.forward();
}
</script>
</head>
<body>

<input type="button" value="Previous" onclick="previous()">


<input type="button" value="Next" onclick="next()">

</body>
</html>

Client Side Scripting (Unit 4) Arrow Computer Academy


JavaScript Popup Boxes

JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

Alert Box
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
window.alert("sometext");

The window.alert() method can be written without the window prefix.

Example
alert("I am an alert box!");

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
alert("I am an alert box!");
}
</script>
</body>
</html>

Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax
window.confirm("sometext");

The window.confirm() method can be written without the window prefix.


Example

if (confirm("Press a button!"))
{
txt = "You pressed OK!";
} else
{
txt = "You pressed Cancel!";
}

Client Side Scripting (Unit 4) Arrow Computer Academy


Program:- <!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var txt;
if (confirm("Press a button!"))
{
txt = "You pressed OK!";
}
else
{
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after
entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns
null.
Syntax
window.prompt("sometext","defaultText");
The window.prompt() method can be written without the window prefix.

Example
var person = prompt("Please enter your name", "Harry Potter");
var text;
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}

Program
<!DOCTYPE html>
<html>

Client Side Scripting (Unit 4) Arrow Computer Academy


<body>

<h2>JavaScript Prompt</h2>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var text;
var person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the character n.

Example
alert("Hello\nHow are you?");
Program

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript</h2>
<p>Line-breaks in a popup box.</p>

<button onclick="alert('Hello\nHow are you?')">Try it</button>

</body>
</html>

Client Side Scripting (Unit 4) Arrow Computer Academy

You might also like