0% found this document useful (0 votes)
53 views111 pages

Chapter 4

This document discusses cookies, including how they work, the different types (session and persistent), and how to create, read, and write cookies using JavaScript. Cookies are small pieces of data stored in the browser that allow sites to remember stateful information about a user. They are created using JavaScript's document.cookie property and can store name-value pairs along with an expiration date.

Uploaded by

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

Chapter 4

This document discusses cookies, including how they work, the different types (session and persistent), and how to create, read, and write cookies using JavaScript. Cookies are small pieces of data stored in the browser that allow sites to remember stateful information about a user. They are created using JavaScript's document.cookie property and can store name-value pairs along with an expiration date.

Uploaded by

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

Chapter 4

Cookies and Browser data


Cookies
• A cookie is a small piece of information store in a file on your
computer.
• This information present in the cookies is accessed by the
web browser.

• 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.
Cookies
• 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 it should
be sent to
Types of cookies
• There are two types of cookies: Session cookies and
persistent cookies
• Session cookies: It is a cookie that remains in temporary
memory only while user is reading , visiting and
navigating the web site. Once you leave the site , the
session cookie is deleted.
• 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 has been reached , then it is deleted.
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 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.
Creating cookies
• For creating a cookie we need to assign cookie value to
window.document.cookie
• Syntax:
• document.cookie = "key1 = value1;key2 = value2;";
• Here name value pair separated by = sign and terminated by a
delimiter like semicolon(;)

• Example:
• document.cookie = “Username = Kimaya;";
Program for Creating cookies
• <html>
• <head>
• <script>

•             function CreateCookie
• {
•                   with(document.form1)
•                        {
•                              document.cookie="Username" + username.value + ";" + alert("Cookie is created");
•                        }
•                                   }
•        </script>      
• </head>

• <body>
• <form name = "form1">
• <input type = "text" name="username" />
•          <input type = "button" value = "Create Cookie" onclick = "CreateCookie()"/>
• </form>
• </body>
• </html>
Read a Cookie

• 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 keep a list of
name=value pairs separated by semicolons, where name
is the name of a cookie and value is its string value.

• You can use strings' split() function to break a string into


key and values as follows −
Read a Cookie Program
<html>
   <head>   
      <script type = "text/javascript">
         
            function ReadCookie() {
                  with(document.form1)
                       {
                             value = document.cookie.split('=')[1];
                            document.write (“ Value : " + value);
               }
            }
       </script>      
   </head>
   
   <body>     
      <form name = “form1“>
         <input type = "button" value = “Read Cookie" onclick = "ReadCookie()"/>
      </form>      
   </body>
</html>
Read a Cookie Program
<html>
   <head>   
      <script type = "text/javascript">
         
            function ReadCookie() {
               var allcookies = document.cookie;
               document.write ("All Cookies : " + allcookies );
               
               // Get all the cookies pairs in an array
               cookiearray = allcookies.split(';');
               
               // Now take key value pair out of this array
Click to add text
               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); Output:
               }
            } click the following button and see the result:
       </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>

 Here length is a method of Array class  which returns the length of an array.


Read a Cookie Program
<html>
<head>
<script >

function ReadCookie() {
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );

// Get all the cookies pairs in an array


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>
Split()
• 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 takes all the
characters to the left of the = and store them into array a[0].

• Next the split() method takes all the characters from the right of the = up to ; but
not including the semicolon and assign those characters to array a[1].

• Thus we can obtain the name value pair in a[0] and a[1] respectively.
Write a cookie
Write a cookie
<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>
Setting Cookies Expiry Date

• Cookies are transient by default i.e. the values they


store last for the duration of the web browser
session but are lost when the user exits the browser.
• 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.
toUTCString() method
• The toUTCString() method converts a Date object to a string, according
to universal time.

•  The Universal Coordinated Time (UTC) is the time set by the World
Time Standard.

• UTC time is the same as GMT(Greenwich Mean Time) time.

• The date object is created using date() constructor.

• Syntax
• Date.toUTCString()
toUTCString() method

<script>
// Here a date has been assigned while creating Date object
var dateobj = new Date('October 15, 2019 05:35:32');

// Contents of above date object is converted into a string using toUTCString()


method.
var B = dateobj.toUTCString();

// Printing the converted string.


document.write(B);
</script>

Output:
Tue, 15 Oct 2019 00:05:32 GMT
new Date()
• The Date object is created by using new
keyword, i.e. new Date(). The Date object can
be used date and time in terms of millisecond
precision within 100 million days before or after
1/1/1970.
• If you create a date without any arguments, you
get a date set to the current time (in Local
Time).
• new Date()
• The setTime() method sets the Date object to
the time represented by a number of
milliseconds since January 1, 1970, 00:00:00
UTC
• Syntax
• Date.setTime(millisec)
• The getTime() method returns the number of
milliseconds between midnight of January 1,
1970 and the specified date.
• Syntax
• Date.getTime()
Calculate the number of years since 1970/01/01:

<html>
<body>
<p>Click the button to calculate the number of years since midnight, January 1, 1970.</p>

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


<p id="demo"></p>
<script>
function myFunction() {
var minutes = 1000 * 60;
var hours = minutes * 60;
var days = hours * 24;
var years = days * 365;
var d = new Date();
var t= d.getTime();
var y = Math.round(t / years);
document.getElementById("demo").innerHTML = y;
}
</script>
</body>
</html>
To display the UTC date and time as a string
<html>
<body>

<p>Click the button to display the UTC date and time as a string.</p>

<input type=button value= Try it onclick ="myFunction()“/>

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

<script>
function myFunction() {
var d = new Date();
var n = d.toUTCString();
document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

• Output:
• Click the button to display the UTC date and time as a string.

• Wed, 29 Jul 2020 05:38:46 GMT


Set cookies with time and get it
<html>
<head>
<script>

function WriteCookie() {
               var d = new Date();    //create an date object
d.setTime( d.getTime() + (1000*60*60*24) ); // set the time to the past. 1000 milliseconds=1 second
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 = "button" value = "Set Cookies" onclick = "WriteCookie()"/>
<input type = "button" value = “Get All Cookies" onclick = “readCookie()"/>

</form>
</body>
</html>
Set cookies with time and get it
<html>
<body>
<script>
// set a cookie
document.cookie=“username=Meenakshi Thalor; expires = Fri,18 dec 2020 12:00:00 GMT ”;
// get a cookie
If(document.cookie)
{
document.write(“Created Cookie is: “+ document.cookie);
cookieString = document.cookie
var list= cookieString.split( “=“ );
document.write(“<br> Split List:” + list);
If( list[0] == “username” )
{
var data = list[1].split( “,” );
document.write(“<br>Data:” +data);
}
}
</script>
</body>
</html>
Example to set and get a cookie.

<head>
</head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Duke Martin";
}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not available");
}
}
</script>

</body>
</html>
display the cookie's name-value pair separately
<html>
<head>
</head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Duke Martin";
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>

</body>
</html>
In this example, we provide choices of color and pass the selected color value to the
cookie. Now, cookie stores the last choice of a user in a browser. So, on reloading the
web page, the user's last choice will be shown on the screen.

<body>
<select id="color" onchange="display()">
<option value="Select Color">Select Color</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>
<script type="text/javascript">
function display()
{
var value = document.getElementById("color").value;
if (value != "Select Color")
{
document.bgColor = value;
document.cookie = "color=" + value;
}
}
window.onload = function ()
{
if (document.cookie.length != 0)
{
var array = document.cookie.split("=");
document.getElementById("color").value = array[1];
document.bgColor = array[1];
}
}
</script>
</body>
The cookie expires attribute provides one of the ways to create a persistent cookie. Here,
a date and time are declared that represents the active period of a cookie. Once the
declared time is passed, a cookie is deleted automatically.

<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Duke Martin; expires=Sun, 20 Nov 2020 12:00:00 UTC";
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
Cookie path attribute
• If a cookie is created for a webpage, by default, it is valid only for the
current directory and sub-directory. JavaScript provides a path attribute to
expand the scope of cookie up to all the pages of a website.

• Cookie path attribute Example


• Let's understand the path attribute with the help of an example.

Here, if we create a cookie for webpage2.html, it is valid only for itself and its sub-directory
(i.e., webpage3.html). It is not valid for webpage1.html file.
In this example, we use path attribute to enhance the visibility of cookies up to all the pages. Here, you all just need to do is to
maintain the above directory structure and put the below program in all three web pages. Now, the cookie is valid for each web page.

<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Duke Martin; max-age=" + (60 * 60 * 24 * 365) + ";path=/;"
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
example to store each name-value pair in a different cookie.

<body>
Name: <input type="text" id="name"><br>
Email: <input type="email" id="email"><br>
Course: <input type="text" id="course"><br>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie = "name=" + document.getElementById("name").value;
document.cookie = "email=" + document.getElementById("email").value;
document.cookie = "course=" + document.getElementById("course").value;
}
function getCookie()
{
if (document.cookie.length != 0)
{
alert("Name="+document.getElementById("name").value+" Email="+document.getElementById("email").value+"
Course="+document.getElementById("course").value);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
Output
Output

• However, if you click, Get Cookie without filling the form, the below dialog
box appears.
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.
Delete cookie
<html>
<head>
<script type = "text/javascript">
function DeleteCookie()
{
var expirydate = new Date();
expirydate.setMonth(expirydate.getMonth() - 1 ); // earlier date of expiry is set
with(document.form1)
{
document.cookie = “UserName" + username.value+”;”
document.cookie = "expires=" + expirydate.toUTCString() + ";“
alert(“Cookie Deleted”);
}
}
</script>
</head>

<body>
<form name = "form1“>
Enter name: <input type = "text" name = “username"/>
<input type = "button" value = “Delete Cookie" onclick = “DeleteCookie()"/>
</form>
</body>
</html>
3 built in functions for setting expiry date of cookie

• getMonth()-This method returns the current month


based on the system clock of the
• computer running the JavaScript.

• setMonth()- This method assigns the month to Date


variable

• toGMTString()- This method returns the value of the Date


variable to a string that is in the format of Greenwich
Mean Time, which is then assigned to the cookie.
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.my
form.customer.value) + ";"

document.cookie = "name=" + cookievalue;


document.cookie = "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>
Set new expiry date of cookies
<html>
<head>
<script>
Function SetExpDtCookie()
{
expiryDate=new Date
expiryDate.setMonth(expiryDate.getMonth()+1)
With(document.form1)
{
Document.cookie=“UserName” +username.value+”;”
Document.cookie=“expires=“ +expiryDate.toUTCString()+”;”
Alert(“New expiry Date is set for the Cookie”);
}
}
</script>
</head>
<body>
<form name=“form1”>
Enter name:<input type=“text” name=“username”/>
<input type=“button” value=“Set New Expiry Date” onclick=“SetExpDtCookie()”/>
</form>
</body>
</html>
Browser
• A browser is an application program that provides a way look at and
interact with all the information on the World Wide Web(WWW).

• Thus a browser is a software used to locate , retrieve and display content


on the internet and World Wide Web, including web pages,images,video
and other files.

• It is possible to open a new browser window from a currently running


JavaScript. One can determine the size, location of this
window,toolbar,scroll bar or any other style that normally the browser
windows have.

• Once the new browser window is set up, it is also possible to change the
contents within that window dynamically.
Methods of window object
• alert() in javascript

• It displays alert dialog box. It has message and ok button.

• <script type="text/javascript">
• function msg(){
• alert("Hello Alert Box");
• }
• </script>
• <input type="button" value="click" onclick="msg()"/>
• confirm() in javascript

• It displays the confirm dialog box. It has message with ok and cancel buttons.

• <script type="text/javascript">
• function msg(){
• var v= confirm("Are u sure?");
• if(v==true){
• alert("ok");
• }
• else{
• alert("cancel");
• }

• }
• </script>

• <input type="button" value="delete record" onclick="msg()"/>
• prompt() in javascript

• It displays prompt dialog box for input. It has message and textfield.

• <script type="text/javascript">
• function msg(){
• var v= prompt("Who are you?");
• alert("I am "+v);

• }
• </script>

• <input type="button" value="click" onclick="msg()"/>
Opening window
• It is possible to open a new window from a
JavaScript by simply clicking a button.
• For that purpose the window object is used.
• This window object has various useful
properties and methods.
• To open a new window we use open() method
of window object.
Window open() Method
• The open() method opens a new browser window, or a new tab, depending on your
browser settings and the parameter values.
• Syntax
window.open(URL, name, style)

• URL- Optional. Specifies the URL of the web 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
_parent - URL is loaded into the parent frame
_self - URL replaces the current page
_top - URL replaces any framesets that may be loaded
name - The name of the window (Note: the name does not specify the title of
the new window)
• Style- It includes various parameters such as toolbar,scrollbar, height, width of window
and so on.
Various styles of window
Layout of window
Program to open a new window

hello.html
<html>
<body>
<script>
document.write(“Hello everybody!!!!”);
</script>
</body>
</html>
Sample.html
<html>
<body>
<script>
var winob=window.open(“hello.html”, “windowName”,
“top=200,left=100,width=250,height=100,status”);
</script>
</body>
</html>
Program to open a new window
<html>
<head>
<script>
function myFunction() {
var mywin= window.open(“https://www.google.com", “windowName",
"top=200,left=100,width=250,height=100,status");
}
</script>
</head>

<body>
<form name=“form1” method=“post”>

<input type=“button” value=“Open Window” onclick="myFunction()“/>

</form>
</body>
</html>
Program to open a new window
<html>
<body>
<p>Click the button to open a new window with some specifications.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
window.open("https://www.w3schools.com", "_blank", "toolbar=yes, scrollbars=yes,
resizable=yes, top=500,left=500,width=400,height=400");
}
</script>

</body>
</html>
Output:
Click the button to open a new window with some specifications .
Close window

Window.close()
This method is used to close the window which are opened by window.open()
method.
Syntax:
window.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>This is 'myWindow'</p>");
}                                                                                                                          

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

</body>
</html>
Close window
<html>
<head>
<title>
window open and close method
</title>
<script>
var Window;

// Function that open the new Window


function windowOpen() {
Window = window.open(
"https://www.geeksforgeeks.org/",
"_blank", "width=400, height=450");
}

// function that Closes the open Window Click to add text


function windowClose() { Click to add text
Window.close();
}
</script>
</head>
<body>
<button onclick="windowOpen()">
Open GeeksforGeeks
</button>
<button onclick="windowClose()">
Close GeeksforGeeks
</button>
</body>
</html>
Giving the new window focus
• The focus and blur events are used to keep track of the elements
the user focuses on.
• Focus-Fires when a focusable element gains the focus.
• Blur-Fires when a focusable element loses the focus.
• The following elements are focusable:
• Window: The focus is gain when the user brings the window
forward and lost when the user sends it back.
• Links: Whether the user uses a keyboard or a mouse.
• Form fields: Whether the user uses a keyboard or a mouse
• Elements with Tabindex: Whether the user uses a keyboard or a
mouse
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.
• This sets the element as the active element in the
current document.
• Only one element can be active at a time in a
document.
• Syntax:
• window.focus()
Giving focus to newly created window
<html>
<head>
<script>
function opennewwindow()
{
var winobj = window.open(“https://www.google.com” , ”windowname”,
”top=200,left=100,width=250,height=100,status”);
winobj.focus();
}
</script>
</head>
<body>
<form method=“post”>
<p>
<input type=“button” name=“openwindow” value=“Open Window” onclick=“opennewwindow()”/>
</p>
</form>
</body>
</html>
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>
• <head>
• <title>
• window Blur and Focus method
• </title>
• <style>
• body {
• text-align: center;
• }

• .gfg {
• font-size: 40px;
• font-weight: bold;
• color: green;
• }
• </style>
• </head>
• <body>
• <div class="gfg">GeeksforGeeks</div>
• <h2>Blur and Focus</h2>
• <script>
• var Window;

• // Function that open the new Window
• function windowOpen() {
• Window = window.open(
• "https://www.geeksforgeeks.org/",
• "_blank", "width=400, height=450");
• }

Output
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 the new window .
• User can make change in the features or
dimensions of window as per the requirement
but a new window is always created on top of
the current window after the button is clicked.
Retrieving window properties
<html>
<head>
<script>

var mywin=window.open(“”, “MyWindow”, “width=500, height=300, top=50, left=75, status=no”);


mywin.document.write(“Screen width=” + mywin.outerWidth);
mywin.document.write(“Screen height=” + mywin.outerHeight);

mywin.document.write(“Screen X=” + mywin. ScreenX);

mywin.document.write(“Screen Y=” + mywin. ScreenY);

mywin.document.write(“<br>Window Name: ” + mywin.name);


mywin.status=“status is ok”
mywin.document.write(“<br>Window status: ” + mywin. status);
</script>
</head>
<html>
Set desired position for the window
<html>
<head>
<script>
function OpenWindowFunction()
{
var mywin=window.open(“”, “MyWindow”, “left=0,top=0,width=200,height=200”)
}
</script>
</head>
<body>
<form name=“form1”>
<input type=“button” value=“Open Window” onclick= “OpenWindowFunction()” />
</form>
</body>
<html>
Output
Window screenX and screenY Properties
<html>
<head>
<script>
function myFunction() {
var myWindow = window.open("", "myWin");
myWindow.document.write("<p>This is 'myWin‘ ");
myWindow.document.write("<br>ScreenX: " + myWindow.screenX);
myWindow.document.write("<br>ScreenY: " + myWindow.screenY + "</p>");
}
</script>
</head>
<body>
<form>
<input type=“button” value=“Open "myWin“ “ onclick="myFunction()“/>
</form>
</body>
</html>
Window Location object
• The window.location object is useful for
finding out the current location or path of the
web page.
• It is used to get the current page address
(URL) and to redirect the browser to a new
page.
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( )
• window.location.href- returns the href (URL) of the current
page
• window.location.host-name returns the domain name of the
web host
• window.location.pathname -returns the path and filename of
the current page
• window.location.protocol -returns the web protocol used
(http: or https:)
• window.location.assign() -loads a new document
• The window.location.port- property returns the number of
the internet host port (of the current page).
To display the pathname of the web page

<html>
<body>
<p id=“ID”> </p>

<script>
document.getElementById(“ID”).innerHTML= “This web page is at path:” + window.location.pathname;
</script>

</body>
</html>
To display the protocol of the web page

<html>
<body>
<p id=“ID”> </p>

<script>
document.getElementById(“ID”).innerHTML= “This web page is using the protocol:” +
window.location.protocol;
</script>

</body>
</html>
Window Location Assign
• <html>
• <head>
• <script>
• function newDoc() {
• window.location.assign("https://www.w3schools.com")
• }
• </script>
• </head>
• <body>

• <input type="button" value="Load new document" onclick="newDoc()">

• </body>
• </html>
Window History object
• The window.history object is used for displaying
browser history.
• There are two important methods of window.browser.
• 1) window.history.back() : This method loads the
previous URL in the history list. It is like clicking Back
button on browser window.
• 2) window.history.forward() : This method loads the
next URL in the history list. It is like clicking Forward
button on browser window.
Display browser history

<html>
<head>
<script>
Function MoveBack()
{
window.history.back();
}

Function MoveForward()
{
window.history.forward();
}

</script>
</head>
<body>
<form name=“form1”>
<input type=“button” value=“Back” onclick=“MoveBack()” />
<input type=“button” value=“Forward” onclick=“MoveForward()” />

</body>
</html>
Changing the contents of Window
• We can change the content of opened new
window as when require.
• We can change the content of the window by
calling the open() method using the same
window name each time.
• By writing some text to the newly created
window we can change the contents of a
window.
JavaScript to write some text using write method

<html>
<head>
<script>
function myFunction() {
var myWindow = window.open("", "myWin“, “width=200”,height=200”);
myWindow.document.write("<p>This line is written in current window</p>");
}
</script>
</head>
<body>
<form>
<input type=“button” value=“Open Window” onclick="myFunction()“/>
</form>
</body>
</html>
Output
Changing the contents of Window
<html>
<body>
<script>
function OpenNewWindow(Ad) {
var winobj = window.open(Ad, "myWin“, “top=200, left=200, width=250”,height=250”);
}
</script>

<input type=“button” name=“Ad” value=“Website 1” onclick=" OpenNewWindow


(‘https://www.google.com’)”/>

<input type=“button” name=“Ad” value=“Website 2” onclick=" OpenNewWindow


(‘https://www.pragationline.com’)”/>

</body>
</html>
Output
Scrolling a web page
• We can scroll horizontally or vertically using scrollTo()
function.

• The scrollTo() method scrolls the document to the specified


coordinates.
• Syntax
• window.scrollTo(xpos, ypos)
Parameter Type Description
xpos Numb Required. The coordinate to scroll to, along the
er x-axis (horizontal), in pixels
ypos Numb Required. The coordinate to scroll to, along the
er y-axis (vertical), in pixels
Scroll document window horizontally

<html>
<head>
<style>
body {
width: 5000px;
}
</style>
</head>
<body>

<p>Click the button to scroll the document window to 500 pixels horizontally.</p>

<button onclick="scrollWin()">Click me to scroll horizontally!</button><br><br>

<script>
function scrollWin() {
window.scrollTo(500, 0);
}
</script>

</body>
</html>
Output
• Click the button to scroll the document window to 500 pixels
horizontally.
Scrolling a web page
<html>
<head>
<script>
function ScrollFunction()
{
window.scrollTo(300,0)
}
</script>
</head>
<body>
<form>
<input type=“button” value=“Scroll ” onclick=“ScrollFunction()“/>
</form>
</body>
</html>
Multiple windows at a glance
<html>
<head>
<script>
function OpenWindowFunction()
{
for (i=0;i<5; i++)
{
var myWindow = window.open("", "myWin“+i, “width=100”,height=100”);
}
}
</script>
</head>
<body>
<form>
<input type=“button” value=“Open Window” onclick=“OpenWindowFunction() “ />

</form>
</body>
</html>
Output
Creating a web page in new window

• We can create a web page using the window


object with the help of write method.
• The only thing is that inside the write() , we
have to write the contents of the web page
with the help of html elements such as
<head>, <body>,<title>,<h1> and so on.
Creating a web page in new window
<html>
<head>
<script>
Function CreateFunction()
{

var mywin=window.open(“”, “MyWindow”, “width=300, height=300”);


mywin.document.write(“<html>”);
mywin.document.write(“<head>”);
mywin.document.write(“<title>WEB SITE DEMO</title>” );
mywin.document.write(“</head>”);
mywin.document.write(“<body>”);
mywin.document.write(“<h2> This is a new Web Page</h2>”);
mywin.document.write(“<h3> Welcome User!!!</h3>”);
mywin.document.write(“</body>”);
mywin.document.write(“</html>”);
}
</script>
</head>
<body>
<form>
<input type=“button” value=“Create Web Page” onclick=“CreateFunction()“ />
</form>
</body>
<html>
Output
Timers
• Using window object it is possible to execute the
code at specified time intervals.
• Window objects provides different timer
functions which allow you to register a function
to be invoked once or repeatedly after a specified
amount of time has elapsed.
• Two functions are supported by window object
for handling timing events and those are-
• 1. setTimeout 2. setInterval
Window setInterval() Method
• The setInterval() method calls a function or evaluates an expression at
specified intervals (in milliseconds).

• The setInterval() method will continue calling the function until


clearInterval() is called, or the window is closed.

• The ID value returned by setInterval() is used as the parameter for the


clearInterval() method.

• 1000 ms = 1 second.

• To execute a function only once, after a specified number of milliseconds,


use the setTimeout() method.
Syntax

• Syntax
setInterval(function, milliseconds, param1, param2, ...)

• Parameter Values

Parameter Description
function Required. The function that will be executed
milliseconds Required. The intervals (in milliseconds) on how often to execute the
code. If the value is less than 10, the value 10 is used
param1, Optional. Additional parameters to pass to the function
param2, ...
Alert "Hello" every 3 seconds

<html>
<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>


<p>After clicking away the alert box, an new alert box will appear in 3 seconds. This goes on forever...</p>
<input type=button value=“Try it “ onclick="myFunction()“/>

<script>
function myFunction() {
setInterval(function() { alert("Hello"); }, 3000);
}
</script>

</body>
</html>
Output:

Click the button to wait 3 seconds, then alert "Hello".


After clicking away the alert box, an new alert box will appear in 3 seconds. This goes on forever...
refer to a "named" function; Alert "Hello" every 3 seconds

<html>
<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>


<p>After clicking away the alert box, an new alert box will appear in 3 seconds. This goes on forever...</p>

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

<script>
var myVar;

function myFunction()
{
myVar = setInterval (alertFunc, 3000);
}

function alertFunc( )
{
alert("Hello!");
}
</script>

</body>
</html>
Display welcome message repeatedly after some specific time interval

<html>
<body>

<p id=“ID”></p>

<script>
var t= setInterval(MyFunction,2000);

function MyFunction()
{
document.getElementById(“ID”).innerHTML + =“<p> Welcome User!!! </p>” ;
}

</script>

</body>
</html>
Display the current time
(the setInterval() method will execute the function once every 1 second, just 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();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
</script>

</body>
</html>

Output:
A script on this page starts this clock:
7:06:25 PM
Using clearInterval() to stop time in the previous example:
<html>
<body>

<p>A script on this page starts this clock:</p>


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

<button onclick="myStopFunction()">Stop time</button>

<script>
var myVar = setInterval(myTimer, 1000);

function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
clearInterval(myVar);
}
</script>

</body>
</html>
Output:
A script on this page starts this clock:
7:09:07 PM
Writing number after a delay using setInterval() method
<html>
<head>
<script>
var num=0;
var timerID=null;

function magic() {
If(timerID===null){ // to avoid multiple registration
timerID= setInterval(“display()” , 500);
}
}
function display() {
If(num>15){
clearInterval(timerID);
return;
}
document.getElementById(“ output “).innerHTML +=num;
num++;
}
</script>
</head>
<body>
<input type=“button” value=“Click Me” onclick=“magic()” />
<textarea id=“ output”></textarea>

</body>
</html>
Toggle between two background colors once every 300 milliseconds:

<html>
<body>

<p>In this example, the setInterval() method executes the setColor() function once every 300 milliseconds, which will toggle between two background colors.</p>

<button onclick="stopColor()">Stop Toggling</button>

<script>
var myVar = setInterval(setColor, 300);

function setColor() {
var x = document.body;
x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}

function stopColor() {
clearInterval(myVar);
}
</script>

</body>
</html>

For Output click on the link:


In this example, the setInterval() method executes the setColor() function once every 300 milliseconds, which will toggle between two background colors.

• https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_setinterval_clearinterval2
Pass parameters to the alertFunc function
<html>
<body>

<p>Click the Start button to output "Hello" once every 2 seconds.</p>

<p>In this example, we also output the parameters that were passed to the alertFunc() function (does not work in IE9 and earlier).</p>

<button onclick="myStartFunction()">Start</button> <button onclick="myStopFunction()">Stop</button>

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

<p id="demo2" style="color:red;"></p>

<script>
var myVar;

function myStartFunction() {
myVar = setInterval(alertFunc, 2000, "First parameter", "Second parameter");
}

function alertFunc(param1, param2) {


document.getElementById("demo").innerHTML += "Hello ";

document.getElementById("demo2").innerHTML = "Parameters passed to alertFunc(): <br>"


+ param1 + "<br>" + param2 + "<br>";
}

function myStopFunction() {
clearInterval(myVar);
}
</script>
</body>
</html>
Output
Click the Start button to output "Hello" once every 2 seconds.
In this example, we also output the parameters that were passed to the
alertFunc() function
Window setTimeout() Method

• The setTimeout() method calls a function or evaluates an


expression after a specified number of milliseconds.

• Tip: 1000 ms = 1 second.

• Tip: The function is only executed once. If you need to


repeat execution, use the setInterval() method.

• Tip: Use the clearTimeout() method to prevent the


function from running.
Syntax

• Syntax
• setTimeout(function, milliseconds, param1, param2, ...)

• Parameter Values
Parameter Description
function Required. The function that will be executed
milliseconds Optional. The number of milliseconds to wait before executing the code.
If omitted, the value 0 is used
param1, Optional. Additional parameters to pass to the function (Not supported
param2, ... in IE9 and earlier)
Program for Alert popup will be displayed 2 seconds
after clicking the button
<html >
<head>
<title>JavaScript Execute a Function after Some Time</title>
</head>
<body>
<script>
function myFunction() {
alert('Hello World!');
}
</script>

<input type=button onclick="setTimeout(myFunction , 2000)“ value= “Click Me” >


</body>
</html>
Display an alert box after 3 seconds

<html>
<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>

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

<script>
function myFunction() {
setTimeout(function(){ alert("Hello"); }, 3000);
}
</script>

</body>
</html>
• Output:
• Click the button to wait 3 seconds, then alert "Hello".
You can also refer to "named" function; Display an alert box after
3 seconds
<html>
<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>

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

<script>
var myVar;

function myFunction() {
myVar = setTimeout(alertFunc, 3000);
}

function alertFunc() {
alert("Hello!");
}
</script>

</body>
</html>
• Output:
• Click the button to wait 3 seconds, then alert "Hello".
Display a timed text:
<html>
<body>

<p>Click on the button below. The input field will tell you when two, four, and six seconds have passed.</p>

<button onclick="timedText()">Display timed text</button>


<input type="text" id="txt">

<script>
function timedText() {
var x = document.getElementById("txt");
setTimeout(function(){ x.value="2 seconds" }, 2000);
setTimeout(function(){ x.value="4 seconds" }, 4000);
setTimeout(function(){ x.value="6 seconds" }, 6000);
}
</script>

</body>
</html>
• Output:
Click on the button below. The input field will tell you when two, four, and six seconds have passed.
Open a new window and close the window after three seconds
<html>
<body>

<p>Click the button to open a new window and close the window after three seconds (3000
milliseconds)</p>

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

<script>
function openWin() {
var myWindow = window.open("", "myWindow", "width=200, height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
setTimeout(function(){ myWindow.close() }, 3000);
}
</script>
</body>
</html>
• Output:
Click the button to open a new window and close the window after three seconds (3000 milliseconds)
A clock created with timing events:
<html>
<body onload="startTime()">

<div id="txt"></div>

<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById("txt").innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(function(){ startTime() }, 500);
}

function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
</script>

</body>
</html>
• Output:
23:00:54
Rotating images using setTimeout() method after 1 sec.
<html>
<head>
<script>
var I,imgs,pic;
function init()
{
pic=document.getElementById(“pic” );
imgs=[“query.png”, “warn.png”, “stop.png” , “info.png” ];
i=0;
rotate();
}
function rotate()
{
pic.src=imgs[i];
(i==(imgs.length-1)) ? i=0; i++;
setTimeout(rotate,1000);
}
document.addEventListner(“DOMContentLoaded”, init, false);
</script>
</head>
<body>
<img id=“pic” width=“120” height=“120” src=“Javascript.jpg”>
</body>
</html>
Moving a car using setTimeout() and clearTimeout() methods
<html>
<head>
<script>
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=

}
document.addEventListner(“DOMContentLoaded”, init, false);
</script>
</head>
<body>
<img id=“pic” width=“120” height=“120” src=“Javascript.jpg”>
</body>
</html>

You might also like