0% found this document useful (0 votes)
4 views

YBS Unit IV Cookies & Browser Data (1)

This document provides an overview of cookies and browser data in JavaScript, explaining how cookies are used for client-side data storage, including their creation, types, and attributes. It details the process of creating, reading, and managing cookies using JavaScript, along with examples of setting cookie attributes like expiration and path. Additionally, it covers browser window manipulation using JavaScript, including opening, focusing, and closing windows, as well as modifying their content.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

YBS Unit IV Cookies & Browser Data (1)

This document provides an overview of cookies and browser data in JavaScript, explaining how cookies are used for client-side data storage, including their creation, types, and attributes. It details the process of creating, reading, and managing cookies using JavaScript, along with examples of setting cookie attributes like expiration and path. Additionally, it covers browser window manipulation using JavaScript, including opening, focusing, and closing windows, as well as modifying their content.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

UNIT IV : COOKIES & BROWSER

DATA

MR. Y. B. SANAP
LECTURER IN IT DEPT.,
GOVERNMENT POLYTECHNIC, AMBAD
Cookies- Basic Of Cookies
2
 Cookies is one of the very efficient way of maintaining state on the client side
 Cookie is stored on client’s machine as a text file
 When the user visits again, the website reads the data from the cookie.
 A cookie is a small text file that lets you store a small amount of data on
the user's computer.
 They are typically used for keeping track of information such as user
preferences that the site can retrieve to personalize the page when user
visits the website next time.
 Cookies are an old client-side storage mechanism that was originally
designed for use by server-side scripting languages.
 Cookies can also be created, accessed, and modified directly using JavaScript,
but the process is little bit complicated and messy.
Cookies- Basic Of Cookies
3
Cookies- Basic Of Cookies
4

Information will get saved once you login, next time cookies data will be used
till the session get closed
Cookies- Basic Of Cookies
5
 Name value
How to create cookie in JavaScript
6
 In JavaScript, we can create, read, update and delete a cookie by using
document.cookie property
Syntax:
document.cookie=“name=value”;
<!DOCTYPE html>
<html>
<head>

</head>
<body>
<script>
document.cookie = "username=geeky";
alert(document.cookie);
</script>
</body>

</html>
//example to set and get a cookie
<!DOCTYPE html>
<html>
<head> <title>Example Cookies</title> </head>
<body>

<input type="button" value="Set Cookie" onclick="setCookie()">


<input type="button" value="Get Cookie" onclick="getCookie()">

<script>
function setCookie()
{
document.cookie = "collegename=gpambad";
}

function getCookie()
{
if(document.cookie!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie is not set");
//display the cookie's name-value pair separately
<!DOCTYPE html>
<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>
Types of Cookies
10

Types of Cookies
1. Session Cookies − These cookies are temporary which are
erased when the user closes the browser. Even if the user logs
in again, a new cookie for that session is created.
2. Persistent cookies − These cookies remain on the hard disk
drive unless user wipes them off or they expire. The Cookie's
expiry is dependent on how long they can last.
JavaScript can create, read or delete a cookies using
document.cookie property.
How to create cookie in JavaScript
11
 When we work with cookie client and server is involved.
 To run the cookie we need server
Cookies- Basic Of Cookies/Cookie Attributes
12

JavaScript provides some optional attributes that enhance the


functionality of cookies. Here, is the list of some attributes with
their description.
Cookie expires attribute
13

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.
//example of cookie expires attribute
<!DOCTYPE html>
<html>
Cookie expire attribute
<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;expires=sat, 20 jan 2022 11: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>
</html>
Cookie max-age attribute
15

The cookie max-age attribute provides another way to create a


persistent cookie. Here, time is declared in seconds. A cookie is
valid up to the declared time only.

document.cookie="username=Duke Martin;max-age=" + (60 * 60 * 24 * 365) + ";"

Here read from right to left

Here age of cookie----


Cookie max-age attribute
16

If I want to active only for 1 minute ..we will write 60 second

If I want to active for half an hour…we will write

document.cookie="username=Duke Martin;max-age="+ (10) + ";";


Here after 10 second cookie will expire
//example of cookie max-age attribute. //display the cookie's name-value pair separately
<!DOCTYPE html>
<html>
<head>
Cookie max-age attribute
</head>
<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="+ (10) + ";";
}
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>
Cookie path attribute
18

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.
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.
//example of cookie max-age attribute.
//display the cookie's name-value pair separately
<!DOCTYPE html>
<html>
Cookie path attribute
<head>
</head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="cookie1=hello;path=/";
}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not available");
}
}
</script>

</body>
</html>
Cookie Domain attribute
20

A JavaScript domain attribute specifies the domain for which the


cookie is valid. Let's suppose if we provide any domain name to
the attribute such like:
domain=javatpoint.com
Here, the cookie is valid for the given domain and all its sub-
domains.
However, if we provide any sub-domain to the attribute such like:
domain=training.javatpoint.com
Here, the cookie is valid only for the given sub-domain. So, it's a
better approach to provide domain name instead of sub-domain.
Browser
21

We can perform various operations with browser window in JS


We can open a new window from currently running JS
We can give focus to the new window.
We can set the position, size and location of new window
We can change the content of the window
We can also perform operation such as scrolling a webpage,
multiple window at a glance, creating a webpage in new window
and closing a window.
Browser
22

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 possible to change
the contents within that window dynamically.
Opening A Window
23

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 & methods.
To open a new windows we use open() method of window
object.
Opening A Window
24
Syntax: window.open(url, name, style);
url: An URL to load into the new window, it specifies the URL of
the new page going to open in new window.
Name: it is used to set the name of the window. It is optional. It
supports following values.
Opening A Window
25
style: style of the window has various parameters such as
scrollbar, toolbar, height, width, location, etc. this is also optional
e.g width=150, height=100
<html>
<body>
Click the button to open new window <br><br>
<button onclick="window.open('https://www.javatpoint.com')"> Open
Window </button>

</body>
</html>
<html>
<body>
<script>
function openWindow() {
window.open('https://www.javatpoint.com');
}
</script>

Click the button to open new window <br><br>


<button onclick="openWindow()"> Open Window </button>
</body>
</html>
//it will display blank window
<html>
<body>
<script>
function openWindow() {
window.open();
}
</script>

Click the button to open new window <br><br>


<button onclick="openWindow()"> Open Window </button>
</body>
</html>
//write a js to open a new window
<html>
<body>
<script>
function openWindow() {
window.open("","","width=200,height=100");
}
</script>

Click the button to open new window <br><br>


<button onclick="openWindow()"> Open Window </button>
</body>
</html>
//write a js to open a new window
<html>
<body>
<script>
function openWindow() {
window.open("https://www.javatpoint.com","","width=200,height=100");
}
</script>

Click the button to open new window <br><br>


<button onclick="openWindow()"> Open Window </button>
</body>
</html>
// In this example, we will specify the _parent at the name parameter. You
can //pass any of these values (_parent, _blank, _top, etc.) in it.
<html>
<script>
function openWindow() {
window.open('https://gmail.com', '_parent');
}
</script>

<body>
<b> Click the button to open new window in same tab </b>
<br><br>
<button onclick="openWindow()"> Open Window </button>
</body>
</html>
// we need to provide any name to the new window and write some text
into //it. This name will pass to the window.open() method
<html>
<script>
function openWindow() {
var newtab =window.open("","anotherWindow","width=300,height=150");
newtab.document.write("<p>This is 'anotherWindow'. It is 300px wide
and 150px tall new window! </p>");
}
</script>

<body>
<b> Click the button to open the new user-defined sized window </b>
<br><br>
<button onclick="openWindow()">Open Window</button>
</body>
</html>
JavaScript Window close method
33
JavaScript provides an in-built function named close() to close the
browser window that is opened by using window.open() method.
Unlike the window.open() method, it does not contain any
parameter. This window.close() method simply close the window
or tab opened by the window.open() method.
Remember that - You have to define a global JavaScript
variable to hold the value returned by window.open() method,
which will be used later by the close() method to close that
opened window.
Syntax: window.close() //this method does not have any parameter
Here, window is the name of that window that is opened by the
window open method.
Close the window opened by window.open()
34

In this example, we will show you how to close the window or tab
opened by the window.open() method. Firstly, we will open a
website URL in a new window (size defined in code) using a
button click and then use another button to close that opened
window. See the below code how it will be done:
<html>
<script>
var newWindow;

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

function closeWindow() {
newWindow.close();
}
</script>
<h3 style="color:brown"> Close Window Example </h3>
<body>
<button onclick="openWindow()">Open New Window</button>
<br><br>
<button onclick="closeWindow()">Close New Window </button>
</body>
</html>
<html>
<head>
<title> Open and close window method example </title>
<script>
var newWindow;
// function to open the new window tab with specified size
function windowOpen() {
newWindow = window.open(
"https://www.javatpoint.com/", "_blank", "width=500, height=350");
}

// function to close the window opened by window.open()


function windowClose() {
newWindow.close();
}
</script>
</head>

<center>
<h2 style="color:green"> Window open() and close() method </h2>
<body>
<b> Click the button to open Javatpoint tutorial site </b><br>
<button onclick="windowOpen()"> Open Javatpoint </button>
<br><br>
<b> Click the button to close Javatpoint tutorial site </b><br>
<button onclick="windowClose()"> Close Javatpoint </button>
</body>
</center>
</html>
<html>
<head>
<title>JavaScript New Window Example</title>
</head>
<script type="text/javascript">
function poponload()
{
testwindow = window.open("https://www.google.com/", "mywindow",
"location=1,status=1,scrollbars=1,width=300,height=400");
testwindow.moveTo(0, 0);
}
</script>
<body onload="javascript: poponload()">
<h1>JavaScript New Window Example</h1>
</body>
</html>
Giving The New Window Focus
38

The focus() method sets focus to the current window.


This method makes a request to bring the current window to the
foreground.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to open a new window with get focus....</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var myWindow = window.open("", "", "width=200,height=100");
myWindow.document.write("<p>A new window!</p>");
myWindow.focus();//or this.focus
}
</script>
</body>
</html>
Window Position
40

We can set the desired position for the window. Using the left &
top attributes values the window position can be set.
<HTML>
<HEAD>
<SCRIPT language="JavaScript">
function new_win()
{
window.open("http://
www.google.com","mywin","width=400,height=300,
screenX=50,left=50,screenY=50,top=50");
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="myform">
<INPUT TYPE="button" value="Open New Window" onClick="new_win()">
</FORM>
</BODY>
</HTML>
Changing The Content Of Window
42

By writing some text to the newly created window we can change
the contents of a window.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to open a new window with Changing the content....</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var myWindow = window.open("", "", "width=200,height=100");
myWindow.document.write("<p>Welcome to CSS... By Current
Window...</p>");
}
</script>
</body>
</html>
Closing A Window
44

The close method closes only windows opened by JavaScript


using the open method.
<!DOCTYPE html> <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>
Scrolling A Web Page
46

We can scroll horizontally or vertically using ScrollTo()


function.
window.scrollTo(xpos,ypos)
xpos: the coordinate to scroll to, along with the x-axis (horizontal),
in pixel
ypos: the coordinate to scroll to, along with the y-axis vertically,in
pixel
//Scroll the document to the horizontal position 500:
//window.scrollTo(500, 0);
<!DOCTYPE html>
<html>
<style>
body {
width: 5000px;
}
</style>

<body>
<h1>The Window Object</h1>
<h2>The scrollTo() Method</h2>

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

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

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

</body>
</html>
//Scroll the document to the vertical position 500::
//window.scrollTo(0, 500);
<!DOCTYPE html>
<html>
<style>
body {
height: 5000px;
}
</style>

<body>
<h1>The Window Object</h1>
<h2>The scrollTo() Method</h2>

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

<button onclick="scrollWin()" style="position:fixed">Scroll to 500 vertically!</button><br><br>

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

</body>
</html>
Multiple Window At Once
49

It is possible to open multiple windows at a time. By using open()


method.
<html>
<head>
<script type="text/javascript">
function open_win()
{
window.open("http://www.java2s.com/")
window.open("http://www.google.com/")
}
</script>
</head>
<body>
<form>
<input type=button value="Open Windows" onclick="open_win()">
</form>
</body>
</html>
Creating A Web Page In New Window
51

We can create a web page using the window object with the help
of write method.
Inside the write() we have to write the content of the web page
with help of the html elements such as <head>,<body>,<h1>.
<HTML> </SCRIPT> </HEAD>
<HEAD> <BODY>
<SCRIPT language="JavaScript"> <FORM name="myform">
<!-- <INPUT TYPE="button" value="Create Web
function new_win() Page" onClick="new_win()">
{ </FORM> </BODY> </HTML>
var mywin=window.open("","mywin","width=400,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...!!!!</h2>");
mywin.document.write("</body>");
mywin.document.write("</html>");

}
JavaScript In URLs
53

JavaScript code can be included on the client side.


JavaScript can be specified in URL using the 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.
For Example: We can type the following code in URL bar:
javascript:alert("Hello World!")
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:
For Example: javascript:var now = new Date(); "The time is:" + now;
JavaScript In URLs
54

JavaScript has several security issues that need attention.


One of the most common JavaScript security vulnerabilities is Cross-
Site Scripting (XSS). Cross-Site Scripting vulnerabilities enable
attackers to manipulate websites to return malicious scripts to visitors.
These malicious scripts then execute on the client side in a manner
determined by the attacker. This vulnerability may cause the user data
theft, account tampering and so on.
Cross-Site Request Forgery(CSRF) is another issue in JavaScript
Cross-Site Request Forgery involves taking over a impersonating a
user’s browser session by hijacking the session cookies. CSRF attacks
can trick the users into executing malicious actions the attacker wants
unauthorized actions on the website.
Timers
55

The window object allows execution of code at specified time


intervals.
These time intervals are called timing events.
The two key methods to use with JavaScript are:
1. setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of
milliseconds.
The first parameter is a function to be executed.
The second parameter indicates the number of milliseconds
before execution.
<!DOCTYPE html>
<html>
<body>
<p>Click "Try it". Wait 5 seconds....</p>
<button onclick="setTimeout(myFunction, 5000);">Try
it</button>
<script>
function myFunction()
{
alert('Hello Message by setTimeout()');
}
</script>
</body>
</html>
<html>
<head>
<title>JavaScript setTimeout() Method</title>
<script type="text/javascript">
function timemsg()
{
var st = setTimeout("alert('5 seconds!')", 2000);
}
</script>
</head>
<body>
<form>
<input type="button" value="Timed Alert Box"
onClick="timemsg()">
</form> </body> </html>
Timers
58

2. setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function
continuously.
The first parameter is the function to be executed.
The second parameter indicates the length of the time-interval
between each execution.
<!DOCTYPE html>
<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>
<html>
<head>
<title>JavaScript setInterval() Method</title>
<script type="text/javascript">
function timemsg()
{
var si = setInterval("alert('2 seconds!')", 2000);
}
</script>
</head>
<body>
<form>
<input type="button" value="Timed Alert Box"
onClick="timemsg()">
</form> </body> </html>
Browser Location
61

When user opens any website, the browser will send the request
to the server. Then the server sends the requested webpage to the
browser. The web page is stored on server. If we want to know the
location or path of the webpage, we use window.location object. It
is used to find the location and path of the current webpage.
 The window.location object is useful for finding out the current location
or path of the web page.
 Properties of window.location as follow:
1. window.location.hostname
2. window.location.pathname
3. window.location.protocol
4. window.location.assign
<!DOCTYPE html>
<html>
<body>
<p id="ID"></p>
<script>
document.getElementById("ID").innerHTML= "This web page
is at path: "+window.location.pathname;
</script>
</body>
</html>

Output: This web page is at path: /C:/Users/lenovo/Desktop/bro.html


<!DOCTYPE html>
<html>
<body>
<p id="ID"></p>
<script>
document.getElementById("ID").innerHTML= "This web page
is using the protocol: "+window.location.protocol;
</script>
</body>
</html>

Output: This web page is using the protocol: https:


<!DOCTYPE html>
<html>
<body>
<p id="ID"></p>
<script>
document.getElementById("ID").innerHTML= "This web page
is using the protocol: "+window.location.hostname;
</script>
</body>
</html>

Output: This web page is using the protocol: localhost


Browser History
65

The window.history object is used for displaying browser


history.
There are two methods window.history as follow:
1. window.history.back() : This method loads the previous URL in
the history list.
2. window.history.forward() : This method loads the next URL in
the history list.
<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()">
</form> </body> </html>
111

You might also like