Unit 4 - Cookies - Browser
Unit 4 - Cookies - Browser
Unit 4
Cookies and Browser Data
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
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;
4.1.3 Write a Cookie with JavaScript
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="">
Enter your name:
<input type="text" name="person"><br>
3
Client-Side Scripting (Semester-V)
With a path parameter, you can tell the browser what path the cookie belongs to.
4
Client-Side Scripting (Semester-V)
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]);
}
else
{
5
Client-Side Scripting (Semester-V)
Code:
<html>
<head>
<script>
function writeCookie()
{
var d=new Date();
d.setTime(d.getTime()+(1000*60*60*24));
6
Client-Side Scripting (Semester-V)
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=Fri,06 Aug 2024 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>
</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
8
Client-Side Scripting (Semester-V)
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.
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.
9
Client-Side Scripting (Semester-V)
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)
is same as
document
Let's see the properties of document object that can be accessed and modified by
the document object.
10
Client-Side Scripting (Semester-V)
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)
getElementsByTagNam returns all the elements having the given tag name.
e()
<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;
}
</style>
</head>
<body>
<div class="example">
14
Client-Side Scripting (Semester-V)
<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";
}
}
</script>
</body>
</html>
Output:
15
Client-Side Scripting (Semester-V)
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;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
16
Client-Side Scripting (Semester-V)
</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)
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.
History It returns the history object for the window.
innerHeig It sets or returns the inner height of a window's content area.
ht
innerWidt It sets or returns the inner width of a window's content area.
h
Length It returns the number of frames in a window.
Location It returns the location object for the window.
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.
open() It opens a new browser window.
createPopup() It creates a pop-up window.
19
Client-Side Scripting (Semester-V)
//save as hello.html
<html>
<body>
<script>
document.write("Hello Everyone!!!!");
</script>
</body>
</html>
//save as sample.html
<html>
20
Client-Side Scripting (Semester-V)
<body>
<script>
var
ob=window.open("hello.html","windowName","top=200,left=100,width=250,height=100,statu
s");
</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()
{
myWindow.close();
}
</script>
21
Client-Side Scripting (Semester-V)
</body>
</html>
Output:
After clicking on “open myWindow” button, new window will be open.
Click on “Close myWindow” button, newly open window will be closed.
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:
window.open("http://vpt.edu.in", "windowName", top=500,left=500,width=400,he
ight=400");
22
Client-Side Scripting (Semester-V)
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
Output:
23
Client-Side Scripting (Semester-V)
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.availWidt returns the width of the visitor's screen, in pixels, minus
h interface features like the Windows Taskbar.
<html>
<body>
24
Client-Side Scripting (Semester-V)
<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 =
"Available screen Height is " + screen.height;
</script>
</body>
</html>
Output:
25
Client-Side Scripting (Semester-V)
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.
Syntax: window.scrollBy(xnum, ynum)
<html>
<head>
<style>
body
{
width: 5000px;
}
button
{
position: fixed;
}
</style>
</head>
<body>
<p>Click the button to scroll the document window by 100px horizontally.</p>
26
Client-Side Scripting (Semester-V)
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()
Code: simple example of moveTo ( )
<html>
<body>
<button onclick="openWin()">Create new window</button>
<button onclick="moveWinTo()">Move new window</button>
<button onclick="moveWinBy()">
Move the new window by 75 * 50px
</button>
<script>
var myWindow;
function openWin()
{
27
Client-Side Scripting (Semester-V)
28
Client-Side Scripting (Semester-V)
<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
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>
30
Client-Side Scripting (Semester-V)
<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>
</body>
</html>
Output:
When user clicks on “Click me to scroll horizontally!” the output will be like this:
31
Client-Side Scripting (Semester-V)
When user clicks on “Click me to scroll vertically!” the output will be like this:
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.
<html>
<head>
32
Client-Side Scripting (Semester-V)
<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');
winobj.focus();
}
}
</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");
34
Client-Side Scripting (Semester-V)
winobj.document.write('<html>');
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>
<iframe src="https://vpt.edu.in/"></iframe>
36
Client-Side Scripting (Semester-V)
</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.
The setTimeout() Method
38
Client-Side Scripting (Semester-V)
window.setTimeout(function, milliseconds);
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>
Output:
39
Client-Side Scripting (Semester-V)
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()
{
alert("Hello");
}
</script>
</body>
</html>
Output:
40
Client-Side Scripting (Semester-V)
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()
{
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>
Output:
window.clearInterval(timerVariable)
41
Client-Side Scripting (Semester-V)
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();
}
</script>
</body>
</html>
Output:
<html>
<body>
<script>
var i,imgs,pic;
function init()
{
42
Client-Side Scripting (Semester-V)
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);
</script>
</head>
<body>
<img id="pic" width="300" height="300">
</body>
</html>
Output:
<html>
<head>
<title>Animation </title>
<script type="text/javascript">
43
Client-Side Scripting (Semester-V)
var obj=null;
var animate;
function init()
{
obj=document.getElementById('car');
obj.style.position='relative';
obj.style.left='0px';
}
function start()
{
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)
<html>
<head>
<title>number </title>
<script type="text/javascript">
var number=0;
var timerId=null;
function magic()
{
if(timerId==null)
{
timerId=setInterval("display()",1000);
}
}
45
Client-Side Scripting (Semester-V)
function display()
{
if(number > 15)
{
clearInterval(timerId);
return;
}
document.getElementById("output").innerHTML+=number;
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>
47
Client-Side Scripting (Semester-V)
</body>
</html>
Output:
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.
48
Client-Side Scripting (Semester-V)
Method Description
assign() It loads a new document.
reload() It reloads the current document.
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
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();
}
50
Client-Side Scripting (Semester-V)
</script>
</body>
</html>
Output:
51