Cookies and Browser Data
Cookies and Browser Data
Unit 4
4.1 Cookies- Basics of Cookies, reading a cookie value, writing a cookie value, creating a
Cookies, deleting a cookie, Setting the expiration Date of Cookies
4.2 Browser-Opening a window, scrolling new window focus, window position, changing the
content of window, closing a window, scrolling a web page, multiple windows at once,
creating a web page in a new window, javascript in URLs, javascript security, Timers, Browser
location and history.
1
Client-Side Scripting (Semester-V)
4.1 Cookies:
4.1.1 Basics of Cookies
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.
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 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.
var x = document.cookie;
You can access the cookie like this which will return all the cookies saved for the current
domain.
2
Client-Side Scripting (Semester-V)
var x = document.cookie;
Change a Cookie with JavaScript
With JavaScript, you can change a cookie the same way as you create it:
<html>
<head>
<script>
function writeCookie()
{
with(document.myform)
{
document.cookie="Name=" + person.value + ";"
alert("Cookie written");
}
}
function readCookie()
{
var x;
if(document.cookie=="")
x="";
else
x=document.cookie;
document.write(x);
}
</script>
</head>
<body>
<form name="myform" action="">
3
Client-Side Scripting (Semester-V)
4
Client-Side Scripting (Semester-V)
With a path parameter, you can tell the browser what path the cookie belongs to.
You don't have to specify a cookie value when you delete a cookie.
<html>
<head>
</head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Vidyalanakr Polytechnic; expires=Mon, 3 Aug 2020
00:00:00 GMT";
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
5
Client-Side Scripting (Semester-V)
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
Output:
Cookies are transient by default; the values they store last for the duration of the web browser
session but are lost when the user exits the browser.
User can extend the life of a cookie beyond the current browser session by setting an
expiration date and saving the expiration date within the cookie.
For example,
Code:
<html>
<head>
<script>
6
Client-Side Scripting (Semester-V)
function writeCookie()
{
var d=new Date();
d.setTime(d.getTime()+(1000*60*60*24));
with(document.myform)
{
document.cookie="Name=" + person.value + ";expires=" +d.toGMTString();
}
}
function readCookie()
{
if(document.cookie=="")
document.write("cookies not found");
else
document.write(document.cookie);
}
</script>
</head>
<body>
<form name="myform" action="">
Enter your name:
<input type="text" name="person"><br>
<input type="Reset" value="Set C" type="button" onclick="writeCookie()">
<input type="Reset" value="Get C" type="button" onclick="readCookie()">
</form>
</body>
</html>
Output:
7
Client-Side Scripting (Semester-V)
Code:
<html>
<head>
<script>
document.cookie="username=VP; expires=Tues,04 Aug 2020 00:00:00 GMT ";
if(document.cookie)
{
document.write("created cookie is:" +document.cookie);
cstr=document.cookie
var list=cstr.split("=");
document.write("<br> Split List:" +list);
if(list[0]=="username")
{
var data=list[1].split(",");
document.write("<br> Data:" +data);
var data=list[2].split(",");
document.write("<br> Data:" +data);
var data=list[3].split(",");
document.write("<br> Data:" +data);
}
}
</script>
</body>
8
Client-Side Scripting (Semester-V)
</html>
Output:
4.2 Browser
A web browser (commonly referred to as a browser) is a software application for retrieving,
presenting and traversing information resources on the World Wide Web. An information
resource is identified by a Uniform Resource Identifier/ Locator (URI/URL) and may be a web
page, image, video or other piece of content. Hyperlinks present in resources enable users easily
to navigate their browsers to related resources.
Although browsers are primarily intended to use the World Wide Web, they can also be used
to access information provided by web servers in private networks or files in file systems.
The major web browsers are Firefox, Internet Explorer, Google Chrome, Opera, and Safari.
Browser's Components:
The browser's main components are:
1. The user interface:
This includes the address bar, back/forward button, bookmarking menu, etc. Every part of the
browser displays except the window where you see the requested page.
2. The browser engine: marshals’ actions between the UI and the rendering engine.
3. The rendering engine:
responsible for displaying requested content. For example, if the requested content is HTML,
the rendering engine parses HTML and CSS, and displays the parsed content on the screen.
4. Networking:
For network calls such as HTTP requests, using different implementations for different platform
behind a platform-independent interface.
9
Client-Side Scripting (Semester-V)
5. UI backend:
Used for drawing basic widgets like combo boxes and windows. This backend exposes a generic
interface that is not platform specific. Underneath it uses operating system user interface
methods.
6. JavaScript interpreter.
Used to parse and execute JavaScript code.
7. Data storage.
This is a persistence layer. The browser may need to save all sorts of data locally, such as cookies.
Browsers also support storage mechanisms such as localStorage, IndexedDB, WebSQL and
Filesystem.
It is important to note that browsers such as Chrome run multiple instances of the rendering
engine: one for each tab. Each tab runs in a separate process.
Document object Model (DOM)
When html document is loaded in the browser, it becomes a document object. It is the root
element that represents the html document. It has properties and methods. By the help of
document object, we can add dynamic content to our web page.
10
Client-Side Scripting (Semester-V)
is same as
document
Let's see the properties of document object that can be accessed and modified by the
document object.
Source: https://www.javatpoint.com/document-object-model
The Document Object Model is a programming API for documents. The object model itself
closely resembles the structure of the documents it models. For instance, consider this table,
taken from an HTML document:
11
Client-Side Scripting (Semester-V)
<TABLE>
<ROWS>
<TR>
<TD>Shady Grove</TD>
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
</TR>
</ROWS>
</TABLE>
Method Description
12
Client-Side Scripting (Semester-V)
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name
Syntax: document.getElementsByClassName(classname);
Code: Find out how many elements with class="example" there are in the document (using
the length property of the HTMLCollection object):
<html>
<body>
<div class="example">
A div element with class="example"
</div>
<div class="example">
Another div element with class="example"
</div>
<p>Click the button to find out how many elements with class "example" there are in this
document.</p>
13
Client-Side Scripting (Semester-V)
<p id="demo"></p>
<script>
function myFunction()
{
var x = document.getElementsByClassName("example");
document.getElementById("demo").innerHTML = x.length;
}
</script>
</body>
</html>
Output:
<html>
<head>
<style>
.example {
border: 1px solid black;
margin: 5px;
14
Client-Side Scripting (Semester-V)
}
</style>
</head>
<body>
<div class="example">
A div with class="example"
</div>
<div class="example">
Another div with class="example"
</div>
<p>Click the button to change the background color of all elements with
class="example".</p>
<script>
function myFunction()
{
var x = document.getElementsByClassName("example");
var i;
for (i = 0; i < x.length; i++)
{
x[i].style.backgroundColor = "red";
}
15
Client-Side Scripting (Semester-V)
}
</script>
</body>
</html>
Output:
In this example, we are going to get the value of input text by user. Here, we are
using document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
value is the property, that returns the value of the input text.
Code: Let's see the simple example of document object that prints name with welcome
message.
<script type="text/javascript">
function printvalue()
{
var name=document.form1.name.value;
16
Client-Side Scripting (Semester-V)
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
Output:
Javascript - innerText
The innerText property can be used to write the dynamic text on the html document. Here, text
will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as writing the validation
message, password strength etc.
Code: In this example, we are going to display the password strength when releases the key
after press.
17
Client-Side Scripting (Semester-V)
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
Output:
Application of DOM:
1) To render a document such as HTML page, most web browsers use an internal model similar
to DOM. The nodes of every document are organized in a tree structure, called DOM tree, with
topmost node named as “Document Object”. When HTML page is rendered in browser, the
browser downloads the HTML page into local memory and automatically parses it to display
the page on screen.
2) When a web page is loaded, the browser creates a Document Object Model of the page,
which is an object-oriented representation of an HTML document, that’s act as an interface
between javascript and document itself and allows the creation of dynamic web pages.
Window object
Property Description
Document It returns the document object for the window (DOM).
Frames It returns an array of all the frames including iframes in the current window.
Closed It returns the Boolean value indicating whether a window has been closed or
not.
18
Client-Side Scripting (Semester-V)
Method Description
alert() It displays an alert box.
confirm() It displays a dialog box.
prompt() It displays a dialog box that prompts the visitor for input.
setInterval() It calls a function or evaluates an expression at specified intervals.
setTimeout() It evaluates an expression after a specified number of milliseconds.
clearInterval() It clears a timer specified by setInterval().
clearTimeOut() It clears a timer specified by setTimeout().
close() It closes the current window.
19
Client-Side Scripting (Semester-V)
//save as hello.html
<html>
<body>
<script>
document.write("Hello Everyone!!!!");
</script>
</body>
20
Client-Side Scripting (Semester-V)
</html>
//save as sample.html
<html>
<body>
<script>
var ob=window.open("hello.html","windowName","top=200,left=100,width=250,height=100,status");
</script>
</body>
</html>
Output:
Code: Open a new window and close that window on button click event using open( ) and
close ( ).
<html>
<body>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
<script>
var myWindow;
function openWin()
{
myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<p>Hello Everyone.Welcome to new window.</p>");
}
function closeWin()
21
Client-Side Scripting (Semester-V)
{
myWindow.close();
}
</script>
</body>
</html>
Output:
<html>
<body>
<button onclick="myFunction()">Open Windows</button>
<script>
function myFunction()
{
window.open("http://www.vpt.edu.in/");
}
</script>
</body>
</html>
22
Client-Side Scripting (Semester-V)
Window position:
A new window always displayed on the screen at the location which is specified by user and
location is specified by setting the left and top properties of new window as shown below:
Syntax:
window.innerWidth
window.innerHeight
The outerWidth property returns the outer width of the browser window, including all interface
elements (like toolbars/scrollbars).
The outerHeight property returns the outer height of the browser window, including all interface
elements (like toolbars/scrollbars).
Syntax:
window.outerWidth
window.outerHeight
<html>
<body>
<div id="demo"></div>
<script>
var txt = "";
txt += "<p>innerWidth: " + window.innerWidth + "</p>";
txt += "<p>innerHeight: " + window.innerHeight + "</p>";
txt += "<p>outerWidth: " + window.outerWidth + "</p>";
23
Client-Side Scripting (Semester-V)
Output:
Window.screen:
Properties:
Proprties Description
screen. availTop Returns the top side of the area on the screen that is available for
application windows.
screen.availLeft Returns the left side of the area on the screen that is available for
application windows.
screen.availWidth returns the width of the visitor's screen, in pixels, minus interface
features like the Windows Taskbar.
screen.availHeight returns the height of the visitor's screen, in pixels, minus interface
features like the Windows Taskbar.
screen.height Returns the vertical resolution of the display screen in pixels.
screen.width Returns the horizontal resolution of the display screen in pixels.
24
Client-Side Scripting (Semester-V)
screen.left Retrieves the horizontal offset of top-left corner of the current screen
relative to the top-left corner of the main screen in pixels.
screen.top Retrieves the vertical offset of top-left corner of the current screen
relative to the top-left corner of the main screen in pixels.
<html>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<p id="demo5"></p>
<p id="demo6"></p>
<p id="demo7"></p>
<script>
document.getElementById("demo").innerHTML =
"Available screen height is " + screen.availHeight;
document.getElementById("demo1").innerHTML =
"Available screen width is " + screen.availWidth;
document.getElementById("demo2").innerHTML =
"Available screen avilable Top is " + screen.availTop;
document.getElementById("demo3").innerHTML =
"Available screen avilable Left is " + screen.availLeft;
document.getElementById("demo4").innerHTML =
"Available screen Top is " + screen.top;
document.getElementById("demo5").innerHTML =
"Available screen Left is " + screen.left;
document.getElementById("demo6").innerHTML =
"Available screen Width is " + screen.width;
document.getElementById("demo7").innerHTML =
25
Client-Side Scripting (Semester-V)
Output:
Window provides two methods which also deal with positioning of windows named scrollBy()
and moveTo() method.
scrollBy(): The scrollBy() method scrolls the document by the specified number of pixels.
<html>
<head>
<style>
body
{
width: 5000px;
}
26
Client-Side Scripting (Semester-V)
button
{
position: fixed;
}
</style>
</head>
<body>
<p>Click the button to scroll the document window by 100px horizontally.</p>
<p>Look at the horizontal scrollbar to see the effect.</p>
<button onclick="scrollWin()">Click me to scroll horizontally!</button><br><br>
<script>
function scrollWin()
{
window.scrollBy(100, 0);
}
</script>
</body>
</html>
Output:
The moveTo() method moves a window's left and top edge to the specified coordinates.
Syntax: window.moveTo(x, y)
The focus() method is used to give focus to an element (if it can be focused).
Syntax: HTMLElementObject.focus()
<html>
<body>
27
Client-Side Scripting (Semester-V)
28
Client-Side Scripting (Semester-V)
We can change the content of opened new window as and when require.
As a new window is created and opened using open() method of window object.
In following example, we are creating only one object of window and each time same window
remain open and content of window changes.
<html>
<body>
<script>
function openWin1(ad)
{
myWindow = window.open(ad, "myWindow", "width=500,height=500");
}
</script>
<button value="Google" onclick="openWin1('https://www.google.com')">Google</button>
<button value="Vidyalankar" onclick="openWin1('http://vpt.edu.in')">Vidyalanakr</button>
</body>
</html>
29
Client-Side Scripting (Semester-V)
Syntax: window.scrollTo(xpos,ypos);
Where,
Xpos: Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels
30
Client-Side Scripting (Semester-V)
Ypos: Required. The coordinate to scroll to, along the y-axis (vertical), in pixels
Code: to scroll the document window to 100 pixels horizontally and vertically.
<html>
<head>
<style>
body
{
width: 5000px;
height: 5000px;
}
</style>
</head>
<body>
<script>
function scrollHorizontal()
{
window.scrollTo(100, 0);
}
function scrollVertical()
{
window.scrollTo(0,100);
}
</script>
<p>Click the button to scroll the document window to 100 pixels horizontally and
vertically.</p>
31
Client-Side Scripting (Semester-V)
</body>
</html>
Output:
When user clicks on “Click me to scroll horizontally!” the output will be like this:
When user clicks on “Click me to scroll vertically!” the output will be like this:
32
Client-Side Scripting (Semester-V)
Creation of multiple window is possible by creating and opening window in a loop using
window.open( ) method.
The only thing needs to take care is to pass proper dimension for window so that newly
created window will not appear one upon another.
Code: In following example, x variable is assigned to top dimension of window and y variable
is assigned to left dimension of window.
<html>
<head>
<title>window </title>
<script type="text/javascript">
function show( )
{
for(i=0; i< 250 ; i=i+50)
{
var x=i+50;
var y=i+50;
winobj=window.open('','win' +i, 'top='+x+ ',left='+y+',width=300, height=200');
}
}
</script>
</head>
<body>
<input type="multiple" value="Show Multiple Windows" type="button" onclick="show()"/>
</body>
</html>
Output:
33
Client-Side Scripting (Semester-V)
You can place dynamic content into a new window by using the document.write( ) method.
All html tags can be written inside document.write( ) method.
Code:
<html>
<head>
<title>window </title>
<script type="text/javascript">
function newWindow()
{
winobj=window.open("","winname","width=300, height=300, left=200, top=200");
winobj.document.write('<html>');
34
Client-Side Scripting (Semester-V)
winobj.document.write('<head>');
winobj.document.write('<title> writing Content</title>');
winobj.document.write('</head>');
winobj.document.write('<body>');
winobj.document.write('<form action="" method="post">');
winobj.document.write('<p>');
winobj.document.write('Enter Inst Name:<input type="text" name="iname">');
winobj.document.write('<br>');
winobj.document.write('<input type="submit" name="submit">');
winobj.document.write('</p>');
winobj.document.write('</form>');
winobj.document.write('</body>');
winobj.document.write('</html>');
winobj.focus();
}
</script>
</head>
<body>
<input type="button" value="New value" onclick="newWindow()">
</body>
</html>
Output:
35
Client-Side Scripting (Semester-V)
Stop()
This method may be useful if the loading of an image or frame takes too long.
Syntax: window.stop();
<html>
<head>
<script>window.stop();</script>
</head>
<body>
<p>The stop() method stops this text and the iframe from loading.</p>
<p><b>Note:</b> This method does not work in Internet Explorer.</p>
36
Client-Side Scripting (Semester-V)
<iframe src="https://vpt.edu.in/"></iframe>
</body>
</html>
Javascript in URL
Another way that 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:
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.
Javascript security
37
Client-Side Scripting (Semester-V)
Timers
• setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.
• setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.
The setTimeout() and setInterval() are both methods of the HTML DOM Window object.
Code: Click a button. Wait 3 seconds, and the page will alert "Hello":
<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>
38
Client-Side Scripting (Semester-V)
Output:
window.clearTimeout(timeoutVariable)
If the function has not already been executed, you can stop the execution by calling
the clearTimeout() method:
Code:
<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>
<script>
function myFunction()
39
Client-Side Scripting (Semester-V)
{
alert("Hello");
}
</script>
</body>
</html>
Output:
window.setInterval(function, milliseconds);
The second parameter indicates the length of the time-interval between each execution.
This example executes a function called "myTimer" once every second (like a digital watch).
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer()
40
Client-Side Scripting (Semester-V)
{
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>
Output:
window.clearInterval(timerVariable)
code:
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>
<script>
var myVar = setInterval(myTimer ,1000);
function myTimer()
{
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
41
Client-Side Scripting (Semester-V)
}
</script>
</body>
</html>
Output:
Code: Rotating images using setTimeout(0 method. Following example is using an array of
images. Using setTimeout(0 method images will be rotated after 1 second.
<html>
<body>
<script>
var i,imgs,pic;
function init()
{
pic=document.getElementById("pic");
imgs=["red.png","blue.png","green.png","yellow.png"];
i=0;
rotate();
}
function rotate()
{
pic.src=imgs[i];
(i==(imgs.length-1))?i=0:i++;
setTimeout(rotate,1000);
}
document.addEventListener("DOMContentLoaded",init,false);
42
Client-Side Scripting (Semester-V)
</script>
</head>
<body>
<img id="pic" width="300" height="300">
</body>
</html>
Output:
<html>
<head>
<title>Animation </title>
<script type="text/javascript">
var obj=null;
var animate;
function init()
{
obj=document.getElementById('car');
obj.style.position='relative';
obj.style.left='0px';
}
function start()
{
43
Client-Side Scripting (Semester-V)
obj.style.left=parseInt(obj.style.left)+ 10 + 'px';
animate=setTimeout(start,20);
}
function stop()
{
clearTimeout(animate);
obj.style.left='0 px';
}
window.onload=init;
</script>
</head>
<body>
<img id="car" src="car.jpg">
<br><br>
<input value="Start" type="button" onclick="start()"/>
<input value="Stop" type="button" onclick="stop()"/>
</body>
</html>
Output:
44
Client-Side Scripting (Semester-V)
Code: Writing a number after a delay using setInterval ( ) method. In this example, numbers
are displayed in a textarea after a 1 second.
<html>
<head>
<title>number </title>
<script type="text/javascript">
var number=0;
var timerId=null;
function magic()
{
if(timerId==null)
{
timerId=setInterval("display()",1000);
}
}
function display()
{
if(number > 15)
{
clearInterval(timerId);
return;
}
document.getElementById("output").innerHTML+=number;
45
Client-Side Scripting (Semester-V)
number++;
}
</script>
</head>
<body>
<button onclick="magic();">
Click me
</button>
<br>
Output:
Navigator Object
• Navigator object is the representation of Internet browser.
• It contains all the information about the visitor's (client) browser.
Navigator Object Properties
Property Description
46
Client-Side Scripting (Semester-V)
userAgent It returns the user agent header sent by the browser to the server.
Method Description
Code:
<html>
<body>
<script type="text/javascript">
document.write("<b>Browser: </b>"+navigator.appName+"<br><br>");
document.write("<b>Browser Version: </b>"+navigator.appVersion+"<br><br>");
document.write("<b>Browser Code: </b>"+navigator.appCodeName+"<br><br>");
document.write("<b>Platform: </b>"+navigator.platform+"<br><br>");
document.write("<b>Cookie Enabled: </b>"+navigator.cookieEnabled+"<br><br>");
document.write("<b>User Agent: </b>"+navigator.userAgent+"<br><br>");
document.write("<b>Java Enabled: </b>"+navigator.javaEnabled()+"<br><br>");
</script>
</body>
</html>
Output:
47
Client-Side Scripting (Semester-V)
Location Object
• Location object is a part of the window object.
• It is accessed through the 'window.location' property.
• It contains the information about the current URL.
Property Description
hash It returns the anchor portion of a URL.
port It returns the port number the server uses for a URL.
Method Description
assign() It loads a new document.
48
Client-Side Scripting (Semester-V)
Code:
<script type="text/javascript">
//note some parts may be blank depending on your URL
alert("hash: " + location.hash + "\n" +
"host: " + location.host + "\n" +
"hostname: " + location.hostname + "\n" +
"href: " + location.href + "\n" +
"pathname: " + location.pathname + "\n" +
"port: " + location.port + "\n" +
"protocol: " + location.protocol + "\n" +
"search: " + location.search );
</script>
Output:
History Object
• History object is a part of the window object.
• It is accessed through the window.history property.
• It contains the information of the URLs visited by the user within a browser window.
49
Client-Side Scripting (Semester-V)
Property Description
Length It returns the number of URLs in the history list.
Next It returns the URL of the next document in the History object.
Previous It returns the URL of the last document in the history object.
Method Description
back() It loads the previous URL in the history list.
<html>
<head>
<title>GeeksforGeeks back() example</title>
</head>
<body>
<b>Press the back button</b>
<input type="button" value="Back" onclick="previousPage()">
<script>
function previousPage() {
window.history.back();
}
</script>
</body>
50
Client-Side Scripting (Semester-V)
</html>
Output:
<!DOCTYPE html>
<html>
<style>
#myProgress
{
width: 100%;
height: 30px;
position: relative;
background-color: #ddd;
}
#myBar
{
background-color: #4CAF50;
width: 5px;
height: 30px;
position: absolute;
}
</style>
<body>
<div id="myProgress">
<div id="myBar">
</div>
</div>
<br>
<button onclick="move()">Click Me</button>
<script>
function move()
{
51
Client-Side Scripting (Semester-V)
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var myVar = setInterval(setColor, 300);
function setColor() {
var x = document.body;
x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}
52
Client-Side Scripting (Semester-V)
function stopColor() {
clearInterval(myVar);
}
</script>
</body>
</html>
<script>
// program to stop the setInterval() method after five times
let count = 0;
// function creation
let interval = setInterval(function(){
}, 2000);
</script>
53