You are on page 1of 55

UNIT 4 08 MARKS

Cookies and
Browser Data
COOKIES-BASICS OF COOKIES
 A cookie is a small text file that lets you store a
small amount of data (nearly 4KB) on the user's
computer. They are typically used for keeping track
of information such as user preferences that the site

Prepared By Mrs.S.J.Patil
can retrieve to personalize the page when user visits
the website next time.
 A cookie is an amount of information that persists
between a server-side and a client-side. A web
browser stores this information at the time of
browsing.
 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.
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.

Prepared By Mrs.S.J.Patil
 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
HOW COOKIES WORKS?
 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.
 So, to recognize the old user, we need to add the

Prepared By Mrs.S.J.Patil
cookie with the response from the server to browser
at the client-side.
 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.
TYPES OF COOKIES
All cookies are not created equal. There are 3 types of them:
 Session: They expire when you close your browser (or if
you stay inactive for a certain time). They’re used for
example on e-commerce websites so you can continue
browsing without losing what you put in your cart.
 Permanent: They persist even when the browser is
closed. They have an expiration date though and by law,

Prepared By Mrs.S.J.Patil
you can’t make them last more than 6 months. They’re
used to remember your passwords and login info so you
don’t have to re-enter them every time.
 Third-party: Cookies attributes usually corresponds to
the website domain they are on. Not for third-party
cookies—as you probably gathered from the name, they
are installed by … third-party websites (no way), such as
advertisers. They gather data about your browsing
habits, and allow them to track you across multiple
websites.Other websites using third-party cookies:
Facebook, Flickr, Google Analytics, Google Maps, Google
Plus, SoundCloud, Tumblr, Twitter and YouTube.
HOW TO CREATE A COOKIE IN JAVASCRIPT?
 In JavaScript, we can create, read, update and delete
a cookie by using
document.cookie property.

Prepared By Mrs.S.J.Patil
 The following syntax is used to create a cookie:

document.cookie="name=value";
AN EXAMPLE TO SET AND GET A COOKIE.
<html>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{

Prepared By Mrs.S.J.Patil
document.cookie="username=Duke Martin";
}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
WRITE COOKIES
 The simplest way to write 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";
Here the expires attribute is optional. If you provide this

Prepared By Mrs.S.J.Patil

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.
 By default, the cookie is deleted when the browser is
closed:
document.cookie = "username=John Doe;
expires=Thu, 18 Dec 2019 12:00:00 UTC";
 With a path parameter, you can tell the browser what
path the cookie belongs to. By default, the cookie belongs
to the current page.
document.cookie = "username=John Doe;
expires=Thu, 18 Dec 2022 12:00:00 UTC; path=/";
Prepared By Mrs.S.J.Patil
READING COOKIES
 Reading a cookie is just as simple as writing one,
because the value of the document.cookie object is
the cookie.
 So you can use this string whenever you want to
access the cookie. The document.cookie string will

Prepared By Mrs.S.J.Patil
keep a list of name=value pairs separated by
semicolons, where name is the name of a cookie
and value is its string value.
var x = document.cookie;
 To get a cookie from the list, you can use the split()
function of strings for breaking the string in the
form of keys and values.
<html>
<head>
<script type = "text/javascript">
document.cookie="username=vijay";
document.cookie="designation=lecturer";
function ReadCookie()
{
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array

Prepared By Mrs.S.J.Patil
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
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>
DELETING A COOKIE
 If the cookie is temporary, it will deleted
automatically after closing the browser.
 There are some situations in which you want to
delete a cookie. The process to delete a cookie is

Prepared By Mrs.S.J.Patil
quite simple. You do not require to specify the value
of a cookie to delete it. To do this, you need to set the
value of the 'expires' attribute to a passed date.

document.cookie = "name=value; expires= Thu, 21 A


ug 2014 16:00:00 UTC; path=/ "
<html>
<head>
<script type = "text/javascript">
function deletecookie()
{
var cookie_value=username.value;
document.cookie="username="+cookie_value+";expires=Thu,01
Jan 1970 00:00:01 GMT";

Prepared By Mrs.S.J.Patil
alert("Cookie is Deleted");
}
</script>
</head>
<body>
<form >
Enter username: <input type = "text" id = "username">
<input type = "button" value = "Delete Cookie" onclick =
"deletecookie()"/>
</form>
</body>
</html>
SETTING THE EXPIRATION DATE OF COOKIE
 You can specify the cookie's lifetime by using
the expires attribute. This attribute gives a way to
create a persistent cookie. Here, the declaration of
time and date represents the active period of a

Prepared By Mrs.S.J.Patil
cookie. Once, the declared time is passed, the cookie
will delete automatically.
 For example:

document.cookie="username=XYZ;expires=Mon, 10
Aug 2040 12:00:00 UTC";
<html>
<head>
<script type = "text/javascript">
function changedate()
{
var now = new Date();
now.setMonth(now.getMonth()+1 );
var cookievalue = username.value;

Prepared By Mrs.S.J.Patil
document.cookie = "name=" + cookievalue+";expires=" + now.toUTCString();
document.write("Expiry date changed to next month for :"
+"Username="+cookievalue);
}
</script>
</head>
<body>

Enter cookie name: <input type = "text" id = "username">


<input type = "button" value = "Extend expiry date" onclick = "changedate()"/>

</body>
</html>
BROWSER
 We can perform various operation with browser
window in JavaScript.
 The Browser Object Model (BOM) is used to

Prepared By Mrs.S.J.Patil
interact with the browser.
Prepared By Mrs.S.J.Patil
WINDOW OBJECT
 The window object represents a window in browser.
An object of window is created automatically by the
browser.
 Methods of window object:

Prepared By Mrs.S.J.Patil
 alert() : It displays alert dialog box. It has
message and ok button.
 Syntax: window.alert(“message”);

or alert(“message”);
Example:

Prepared By Mrs.S.J.Patil
<script type="text/javascript">
function msg()
{
alert("Hello Alert Box");
}
</script>
<input type="button" value="click" onclick="msg()"
/>
 prompt() :The prompt () method displays a dialog
box that prompts the visitor for input. The prompt ()
method returns the input value if the user clicks
"OK". If the user clicks "cancel" the method returns
null.
 Syntax: window.prompt (text, defaultText)

Prepared By Mrs.S.J.Patil
 confirm() :It displays the confirm dialog box. It
has message with ok and cancel buttons. Returns
Boolean indicating which button was pressed
Syntax: window.confirm("sometext");

Prepared By Mrs.S.J.Patil
OPENING A WINDOW- OPEN() METHOD
 The open() method of window object is used to open
a new window and loads the document specified by a
given URL.
MyWindow = window.open()

Prepared By Mrs.S.J.Patil
 The open() method returns a reference to the new
window, which is assigned to the MyWindow
variable.
 You then use this reference any time that you want
to do something with the window while your
JavaScript runs.
 A window has many properties, such as its width,
height, content, and name—to mention a few. You
set these attributes when you create the window by
passing them as parameters to the open() method:
 The first parameter is the full or relative URL of
the web page that will appear in the new window.
 The second parameter is the name that you assign
to the window.
 The third parameter is a string that contains the
style of the window. We want to open a new window

Prepared By Mrs.S.J.Patil
that has a height and a width of 250 pixels and
displays an advertisement that is an image. All
other styles are turned off.
 Syntax:

MyWindow = window.open(‘webpage1.html’,
'myAdWin', 'status=0, toolbar=0, location=0,
menubar=0, directories=0, resizeable=0, height=250,
width=250')
Prepared By Mrs.S.J.Patil
GIVING NEW WINDOW FOCUS
 Window.focus() Method
The focus() method is used to focus on the new open
window. i.e bringing back the blur window to the
foreground.

Prepared By Mrs.S.J.Patil
 Syntax: window.focus()

 Window.blur() Method
The blur() method is used to remove focus from the
current window. i.e, It send the new open Window to
the background.
 Syntax: window.blur()
<html>
<body>
<h1>The Window Object</h1>
<h2>The focus() and blur()Method</h2>
<p>Click the button to open a new window, and set focus to it and blur</p>
<button onclick="myFunction()">focus</button>
<button onclick="myFunction1()">blur</button>
<script>
function myFunction()

Prepared By Mrs.S.J.Patil
{
const myWindow = window.open("", "", "width=200,height=100");
myWindow.focus();

}
function myFunction1()
{
var myWindow = window.open("", "", "width=200, height=100");
myWindow.blur();
}
</script>
</body>
</html>
WINDOW POSITION
 The position of window object can be retrieved and
changed using various properties and methods.
1. The moveTo() method moves a window to the
specified coordinates.

Prepared By Mrs.S.J.Patil
2. This function moves the window to absolute
location.
Syntax: window.moveTo(x,y);

2. The moveBy() method moves a window a number of


pixels relative to its current coordinates.
3. This function moves window relative to its current
location.
Syntax: window.moveBy(x,y);
<html>
<body>
<h1>The Window Object</h1>
<h2>The moveTo() and moveBy() Method</h2>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="moveWin()">Move "myWindow"</button>
<button onclick="moveWin1()">Move "myWindow1"</button>
<script>

Prepared By Mrs.S.J.Patil
let myWindow;
function openWin() {
myWindow=window.open("", "", "width=400, height=200");
}
function moveWin() {
myWindow.moveTo(500, 100);
}
function moveWin1() {
myWindow.moveBy(250, 250);
}
</script>
</body>
</html>
CHANGING THE CONTENT OF THE WINDOW
 The innerHTML property can be used to write the
dynamic html on the html document.
 Basically ,it is use to change the web content without
refreshing the page.

Prepared By Mrs.S.J.Patil
 The innerHTML is a property of the element that allows
you to get or set the HTML mark-up contained within
the element.
 It returns the current HTML source of the element ,
including any change that has been made since the page
was loaded.

document.getElementById(‘ID of Element’).innerHTML=‘{content}’;
<html>
<head> <title> Window object Example </title> </head>
<body>
<script>
function msg1()
{
document.getElementById('mytext').innerHTML="Javascript";

Prepared By Mrs.S.J.Patil
}

function msg2()
{
document.getElementById('mytext').innerHTML="CSS";
}
</script>
<input type="button" onclick="msg1()" value="show1">
<input type="button" onclick="msg2()" value="show2">
<p id="mytext"> Hello World</p>
</body>
</html>
CLOSING WINDOW
 The close() method closes a window.
 Syntax: window.close()
<html>
<body>
<h1>The Window Object</h1>
<h2>The open() and close() Methods</h2>
<button onclick="openWin()">Open "myWindow"</button>

Prepared By Mrs.S.J.Patil
<button onclick="closeWin()">Close "myWindow"</button>
<script>
let myWindow;
function openWin()
{
myWindow = window.open("", "", "width=200,height=100");
}
function closeWin()
{
myWindow.close();
}
</script>
</body>
</html>
SCROLLING A WEB PAGE
 Basically ,scrollTo() and scrollBy() methods are used
to make a web page scroll horizontally and
Vertically.
1. The scrollTo() method scrolls the document to

Prepared By Mrs.S.J.Patil
specified coordinates.
 Syntax: window.scrollTo(x, y) or scrollTo(x, y)

2. The scrollBy() method scrolls the document by the


specified number of pixels.
 Syntax: window.scrollBy(x, y) or scrollBy(x, y)
<html>
<style>
body
{
width: 5000px;
}
</style>
<body>
<h1>The Window Object</h1>

Prepared By Mrs.S.J.Patil
<h2>The scrollTo() Method</h2>

<p>Click to scroll the document.</p>

<button onclick="scrollWin()" style="position:fixed">Scroll to 200


horizontally!</button><br><br>

<script>
function scrollWin()
{
window.scrollTo(200, 0);
}
</script>
</body>
</html>
<html>
<style>
body {width: 5000px}
button {position:fixed}
</style>
<body>
<h1>The Window Object</h1>
<h2>The scrollBy() Method</h2>

Prepared By Mrs.S.J.Patil
<p>Click to scroll the document.</p>

<p>Look at the horizontal scrollbar to see the effect.</p>

<button onclick="scrollWin()" style="position:fixed">Scroll 100px


horizontally!</button>
<br><br>
<script>
function scrollWin()
{
window.scrollBy(100, 0);
}
</script>
</body>
</html>
<p>B</p>
<html> <br>
<body> <br>
<br>
<h1>The Window Object</h1> <p>C</p>
<h2>The scrollBy() Method</h2> <br>
<br>
<p>Click to scroll the <br>
document.</p>
<p>D</p>

Prepared By Mrs.S.J.Patil
<br>
<button onclick="scrollWin()"
style="position:fixed">Scroll <br>
100px vertically!</button> <br>
<br><br> <script>
<h3>Some line breaks to enable function scrollWin()
scrolling:</h3> {
<br> window.scrollBy(0, 100);
<br> }
<br> </script>
<p>A</p> </body>
<br> </html>
<br>
<br>
MULTIPLE WINDOWS AT ONCE
 There are two ways to open multiple windows on a single click:
 Create a loop to call window.open(‘url’)method multiple times on onclick event.
<html>
<head>
<title>opening multiple windows at a time</title>
<script>

Prepared By Mrs.S.J.Patil
function createwin()
{
for(var i=0;i<5;i++)
{
var mywin=window.open("","win“+i,"width=100,height=100");
}
}
</script>
</head>
<body>
<form>
<input type="button" value="create window" onclick="createwin()">
</form>
</body>
</html>
 Second way,to write window.open(‘url’) method multiple times
without using for loop.
<html>
<head>
<title>opening multiple windows</title>
<script>
function openwin()
{

Prepared By Mrs.S.J.Patil
window.open("radio.html","","width=100,height=100");
window.open("focus.html","","width=100,height=100");
}
</script>
</head>
<body>
<form>
<input type="button" value="open window" onclick="openwin()">
</form>
</body>
</html>
CREATING A PAGE IN NEW WINDOW
 We can create a web page in a new window with the
help of document.write() function of document object
by adding the HTML element as a string inside the
write() function.

Prepared By Mrs.S.J.Patil
<html>
<head>
<script>
function openwin()
{
var s=window.open("NEW Window","","width=500,height=200");
s.document.write("<html>");
s.document.write("<head>");

Prepared By Mrs.S.J.Patil
s.document.write("<title>");
s.document.write("MSBTE Website");
s.document.write("</title>");
s.document.write("</head>");
s.document.write("<body>");
s.document.write("<h5> Welcome To MSBTE Website</h5>");
s.document.write("</body>");
s.document.write("</html>");
}
</script>
</head>
<body>
<input type ="button" value="new window" onclick="openwin()">
</body>
</html>
JAVASCRIPT IN URL’S
url object:
 The built in URL class provides a convenient
interface for creating and parsing URLs.
 Syntax:

Prepared By Mrs.S.J.Patil
new URL(url ,[Base])

Here, url-full url or only path


Base-an optional base url; if set and url
argument has only path , then the url is
generated relative to base.
 Example:

let url=new URL(‘https://abc.info/profile/admin’);


The URL object components can be access by
following ways:
Let url=new URL(‘https://abc.info/url’);
alert(url.protocol); //https
alert(url.host); //abc.info

Prepared By Mrs.S.J.Patil
alert(url.pathname) // /url
JAVASCRIPT SECURITY
 Ways of protecting Web Page:
1)Hiding your source code
2)Disabling the right MouseButton

Prepared By Mrs.S.J.Patil
3) Hiding JavaScript
4) Concealing E-mail address.

1)Hiding your source code:


First, you can disable use of the right mouse
button on your site so the visitor can't access the
View Source menu option on the context menu.
This hides both your HTML code and your
JavaScript from the visitor.
2)Disabling the right MouseButton:
 All the action occurs in the JavaScript that is defined
in the tag of the web page. The JavaScript begins by
defining the BreakInDetected() function.
 This function is called any time the visitor clicks the

Prepared By Mrs.S.J.Patil
right mouse button while the web page is displayed.
 It displays a security violation message in a dialog
box whenever a visitor clicks the right mouse button
The BreakInDetected() function is called if the
visitor clicks any button other than the left mouse
button.
3) Hiding JavaScript
 You can hide your JavaScript from a visitor by
storing it in an external file on your web server.
 The external file should have the .js file extension.
The browser then calls the external file whenever the
browser encounters a JavaScript element in the web

Prepared By Mrs.S.J.Patil
page.
 If you look at the source code for the web page, you'll
see reference to the external .js file, but you won't see
the source code for the JavaScript.
4) Concealing E-mail address:
 Some spammers create programs called bots that
surf the Net looking for e-mail addresses that are
embedded into web pages, such as those placed there
by developers to enable visitors to contact them.
 The bots then strip these e-mail addresses from the

Prepared By Mrs.S.J.Patil
web page and store them for use in a spam attack.
This technique places developers between a rock and
a hard place.
 If they place their e-mail addresses on the web page,
they might get slammed by spammers.
 If they don't display their e-mail addresses, visitors
will not be able to get in touch with the developers.
The solution to this common problem is to conceal
your e-mail address in the source code of your web
page so that bots can't find it but so that it still
appears on the web page.
JAVASCRIPT TIMER
 A timer is a function that enables us to execute a
function at a particular time.
 Using timers you can delay the execution of code
so that it does not get done at the exact moment
an event is triggered or the page is loaded.

Prepared By Mrs.S.J.Patil
 For example, you can use timers to change the
advertisement banners on your website at
regular intervals, or display a real-time clock, etc.
 There are two timer functions in
JavaScript: setTimeout() and setInterval().
1. setTimeout():
 The setTimeout() function is used to execute a
function or specified piece of code just once after
a certain period of time. Its basic syntax
is setTimeout(function, milliseconds).
 This function accepts two parameters: a function,

Prepared By Mrs.S.J.Patil
which is the function to execute, and an
optional delay parameter, which is the number of
milliseconds representing the amount of time to
wait before executing the function (1 second =
1000 milliseconds).
2. setInterval():
 Similarly, you can use the setInterval() function
to execute a function or specified piece of code
repeatedly at fixed time intervals. Its basic
syntax is setInterval(function, milliseconds).
 This function also accepts two parameters:

Prepared By Mrs.S.J.Patil
a function, which is the function to execute,
and interval, which is the number of milliseconds
representing the amount of time to wait before
executing the function (1 second = 1000
milliseconds).
 Example of setTimeout():
<html >
<head>
<title>JavaScript Execute a Function after Some Time</title>
</head>
<body>
<script>

Prepared By Mrs.S.J.Patil
function myFunction()
{
alert('Hello World!');
}
</script>

<button onclick="setTimeout(myFunction, 2000)">Click


Me</button>
<p><strong>Note:</strong> Alert popup will be displayed 2
seconds after clicking the button.</p>
</body>
</html>
 Example of setInterval():
<html>
<head>
<title>JavaScript Execute a Function at Regular
Intervals</title>
</head>
<body>
<script>

Prepared By Mrs.S.J.Patil
function showTime()
{
var d = new Date();
document.getElementById("clock").innerHTML =
d.toLocaleTimeString();
}
setInterval(showTime, 1000);
</script>
<p>The current time on your computer is: <span
id="clock"></span></p>
</body>
</html>
BROWSER LOCATION AND HISTORY
Location Object: (Syntax: window.location or location)
 The location object in JavaScript helps in storing the
information of current URL of the window object ; it is
child object of the window object.
 It is represents the current location(URL) of a

Prepared By Mrs.S.J.Patil
document; the location can be access by referencing
the location property of the window or document
object.
 Both window.location and document.location link to
the same location object.
 Properties of location object: 1. hash 2. host 3.
hostname 4. href 5. origin 6. pathname 7. port 8.
protocol 9. search
 Methods of location object: 1. assign( ) 2. reload( )
3. replace( )
//Example of Location Object
<html>
<body>
<h2>JavaScript</h2>
<h3>The window.location object</h3>
<input type="button" value="Load new document"

Prepared By Mrs.S.J.Patil
onclick="newDoc()">
<script>
function newDoc()
{
window.location.assign("https://www.w3schools.com")
}
</script>
</body>
</html>
HISTORY OBJECT

 The JavaScript history object represents an array of


URLs visited by the user. By using this object, you can
load previous, forward or any particular page.
 The history object is the window property, so it can be
accessed by:

Prepared By Mrs.S.J.Patil
window.history or history
 Property of JavaScript history object

1. length returns the length of the history URLs.


 Methods of JavaScript history object

No. Method Description


1 forward() loads the next page.
2 back() loads the previous page.
3 go() loads the given page number.
Example:
 history.back();//for previous page

 history.forward();//for next page

 history.go(2);//for next 2nd page

 history.go(-2);//for previous 2nd page

Prepared By Mrs.S.J.Patil
<html>
<head>
<script>
function goForward()
{
window.history.forward()
}

Prepared By Mrs.S.J.Patil
function goBack()
{
window.history.back()
}
</script>
</head>
<body>
<input type="button" value="Forward" onclick="goForward()">
<input type="button" value="Back" onclick="goBack()">
</body>
</html>

You might also like