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

CSS Unit 4. Cookies and Browser Data

Cookie

Uploaded by

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

CSS Unit 4. Cookies and Browser Data

Cookie

Uploaded by

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

Unit 4

Cookies and Browser Data (08 Marks)


Cookies
• Cookies are the name given to the small text files your browser
stores on your computer, which contain information relevant to
the sites you have visited in the past.

• Using JavaScript you can write to these text files and then extract
data from them whenever your reader returns to your site.

• Cookies are small pieces of text sent to your browser by a website


you visit. They help that website remember information about your
visit, which can both make it easier to visit the site again and make
the site more useful to you.
Cookies Cont..
Cookies remembers the information about the user in the
following ways
• Step 1: when the user visit the webpage his/her is name can
be stored in a cookie.
• Step 2: to next time when the user visit the same page, the
cookie remembers his/her name. Cookies
are saved in a name-value pair,

• for example-
username = AAABBB
• Cookies is a small text field which contain following data
1. A name-value pair which stores whatever data you want
to save.
2. An expiry date, after which time the entry will be deleted.
3. The web domain and path that the entry should be
associated with.
Cookies Cont..
• There are two types of cookies:
1. session cookies
2. persistent cookies
1. Session cookies:
session cookies are a cookie that remains in a temporary
memory only while user is reading and navigating the
website. The cookies are automatically deleted when the
user exits the browser application.
2. Persistent cookies:
A persistent cookies is a cookie that is assigned an
expiration date. A persistent cookie is return to the
computer's hard disk and remains there until the expiration
date has been reached; then it is deleted.
• JavaScript can create, read and delete a cookie using
document. cookie property.
Cookies Cont..
Creating Cookies
• With JavaScript, a cookie can be created like this:
document. cookie = "username=John";
Thus the name value pair separated by ‘=’ sign and terminated by
a delimiter like semicolon (;) You can also add an expiry date (in
UTC time).
• By default, the cookie is deleted when the
browser is closed:
document. cookie = "username=John; expires=Thu, 18 Dec 2013
12:00:00 UTC";
• With a path parameter, you can tell the browser what path the
cookie belongs to. By default, the cookie belongs to the current
page.
• document. cookie = "username=John; expires=Thu, 18 Dec
2013 12:00:00 UTC; path=/";
JavaScript Program to display cookie
<html>
<head>
<script type = "text/javascript">
document.cookie = "name=oeschger";
document.cookie = "favorite_food=tripe";
function alertCookie() {
alert(document.cookie);
}
</script></head>
<body>
<button onclick="alertCookie()">Show cookies</button>
</body>
</html>
JavaScript Program to set and get cookie
<!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=Ram";
}function getCookie(){
if(document.cookie.length!=0)
{alert(document.cookie);
}else{
alert("Cookie not available");
}}</script></body></html>
Cookies Cont..
Reading a cookie value

• Reading a cookie is as simple as writing one because of the value of the


document.cookie object is the cookie.
• You can use this string whenever you want to access the cookie. The
document.cookie string keeps a list of name=value pairs separated
by semicolons, where name represents the cookie name and value is its
string value.
• Using split() function the string of cookies break into key and values.

1. The split() method finds the = character in the cookie, and then takes
all the character to left of the = and store them into an array array[0].
2. Next split() method takes all the characters from right of the = up to;
3. but not including the semicolon, and assign those characters to

JavaScript Cookies can be read in the following way:


var x = document.cookie;
JavaScript Program to read cookie
<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
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 Button to View Result:</p>
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form></body></html>
Cookies Cont..
• Deleting Cookies
3 Different ways to delete a Cookie
These are the following ways to delete a cookie:
1. A cookie can be deleted by using expire attribute.
2. A cookie can also be deleted by using max-age attribute.
3. We can delete a cookie explicitly, by using a web browser.
JavaScript Program to delete a cookie by providing expiry date (i.e. any
past date)
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="name=Martin ; expires=Sun, 20 Aug 2000 12:00:00 UTC";

}function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{alert("Cookie not avaliable");
}
}</script></body></html>
JavaScript Program use max-age attribute to delete a cookie by providing
zero or negative number (that represents seconds) to it.
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<script>
function setCookie(){
document.cookie="name=Martin ;max-age=0";
}function getCookie()
{if(document.cookie.length!=0)
{alert(document.cookie);
}else
{alert("Cookie not avaliable");
}} </script></body></html>
JavaScript Program to set and get cookies.
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<script>
function setCookie()
{document.cookie="name=Martin ";
}function getCookie()
{if(document.cookie.length!=0)
{alert(document.cookie);
}else
{alert("Cookie not avaliable");
}}</script></body></html>
Cookies Cont..
• Deleting Cookies
To delete a cookie explicitly, follow the following steps:
1. Open Mozilla Firefox.
2. Click Open menu - Library - History - Clear Recent History -
Details.
Cookies Cont..
• Deleting Cookies
Cookies Cont..
• Setting Expiration Date of Cookies
• This can be done by setting the ‘expires’ attribute to a date and
time.
we need three important built in function

1. getMonth()- this method returns the current month based on the system
clock of the computer running the JavaScript.
2. setMonth()- this method assigns the month to Date variable.setMonth(0)

3. toGMTString()- this method returns the value of the Date variable to a


string that is in the format of time. Which is then assigned to the cookie.
JavaScript Program to display cookies by getMonth.
<html>
<head>
<title>JavaScript getMonth Method</title>
</head>
<body>
<p>getMonth() returns the month (from 0 to 11) of a date:</p>
<script type = "text/javascript">
var dt = new Date();
document.write("getMonth() : " + dt.getMonth() );
</script>
<p><strong>Note:</strong> 0=January, 1=February etc.</p>
</body>
</html>
JavaScript Program to display cookies by setMonth.
<html>
<head>
<title>JavaScript setMonth Method</title>
</head>

<body>
<script type = "text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setMonth( 2 );//Month index start from 0
document.write( dt );
</script>
</body>
</html>
JavaScript Program to display cookies by toGMTString Method.
<html>
<head>
<title>JavaScript toGMTString Method</title>
</head>
<body>
<script type = "text/javascript">
var dt = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : " + dt.toGMTString() );
</script>
</body>
</html>
JavaScript Program to display cookies by setcookie Method.
<html><head><script>
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = document.myform.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>
Browser
Browser
• 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.
Opening a 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.
Opening a Window Cont..
• Syntax
The syntax of using open() method is
window.open(URL, name. style)

Where,
URL: The URL specifies the URL of the web page that will
appear in new window. This is an optional parameter.

name: The name that could be assigned to a window. This is an


optional parameter

style: The style of the window includes various parameters


such as toolbar, scrollbar, location, height and width of window
and so on
Opening a Window Cont..
Sr.N Parameters Description
o
1 channelmode=yes|no|1|0 Whether or not to display the window in theater
mode. Default is no. IE only

2
directories=yes|no|1|0 Obsolete. Whether or not to add directory buttons.
Default is yes. IE only
3
fullscreen=yes|no|1|0 Whether or not to display the browser in full-screen
mode. Default is no.

4 height=pixels
The height of the window. Min. value is 100
5
left=pixels The left position of the window. Negative values not
allowed
6 location=yes|no|1|0
Whether or not to display the address field. Opera only
Opening a Window Cont..
Sr.No Parameters Description

7
menubar=yes|no|1|0 Whether or not to display the menu bar
8
resizable=yes|no|1|0 Whether or not the window is resizable.
IE only
9
scrollbars=yes|no|1|0 Whether or not to display scroll bars. IE,
Firefox & Opera only
10
status=yes|no|1|0 Whether or not to add a status bar
11
titlebar=yes|no|1|0 Whether or not to display the title bar.
Ignored unless the calling application is
an HTML Application or a trusted
dialog box
12
toolbar=yes|no|1|0 Whether or not to display the browser
toolbar. IE and Firefox only
13
top=pixels The top position of the window. Negative
values not allowed
Opening a Window Cont..

Sr. No Parameters Description

13
top=pixels The top position of the window. Negative values
not allowed
14 width=pixels The width of the window. Min. value is 100

• Return value

A newly created window gets opened up on success and


null on failure.
Layout and part of Window
JavaScript Program to OPEN NEW blank Window

<!DOCTYPE html>
<html>
<body>
<p>Click the button to open an about:blank page in a new
browser window that is 200px wide and 100px tall.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var myWindow = window.open("", "", "width=200,height=100");
}
</script>
</body>
</html>
JavaScript Program to OPEN NEW Window with website

<!DOCTYPE html>
<html>
<body>
<p>Click the button to open a new browser window.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
window.open("https://www.w3schools.com");
}
</script>
</body>
</html>
New Window Focus
• A focus to a new window can be giving using focus()
method.
JavaScript Program to set new window focus using Focus method
<!DOCTYPE html>
<html>
<body>
<p>Click the button to open a new window, and assure that the new
window GETS focus
(send the new window to the front).</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();
}
</script>
</body>
</html>
Window Position
• We can set the desired position for the window.
• Using the left and top attribute values the window
position can be set.
• style attribute as left=0, top=0 in open method, the window
is created and positioned at the extreme left and top
location screen
JavaScript Program to set new window position
<!DOCTYPE html>
<html>
<body>
<p>Click the button to open a new window with some specifications.</p>
<button onclick="myFunction()">Open Window</button>
<script>
function myFunction() {
window.open("https://www.google.com","_blank","toolbar=yes,scrollbars=ye
s,resizable
=yes,top=0,left=0,width=400,height=400");
}
</script>
</body>
</html>
Changing Window Content
• By writing some text to the newly created window we can
change the contents of a window
JavaScript Program to change the content of window

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Open Window</button>
<script>
function myFunction()
{
var myWindow = window.open("", "", "width=200,height=100");

myWindow.document.write("<p>A new window!</p>");


}
</script>
</body>
</html>
Close Window

• The most simple operation about the window is to close it. It


can be close using the function close().
JavaScript Program to close the window

<!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 Web Page
• We can scroll horizontally or vertically using scrollTo()
function.
• Second Program see on page no.21
JavaScript Program to Scroll the Web Page.
<!DOCTYPE html>
<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>
Multiple Windows at Once
• It is possible to open up multiple windows at a time.
Simply put open() method multiple time
JavaScript Program to open Multiple Windows at Once.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to open multiple tabs.</p>
<button onclick="myFunction()">Open Windows</button>
<button onclick="myf2()">Open Windows</button>
<button onclick="myf3()">Open Windows</button>
<script>
function myFunction() {
window.open("http://www.google.com/");
}
function myf2()
{
window.open("https://www.w3schools.com/");
} function myf3()
{
window.open("https://www.gmail.com/");
}</script></body></html>
Creating 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 element
such as <head>, <body>, <title>,<h1> and so on.
JavaScript Program to create web page in new window
<!DOCTYPE html>
<html><head>
<script>
function myFunction() {
var myWin = window.open("", "myWindow", "width=300,height=300");
myWin.document.write("<html>");
myWin.document.write("<head>");
myWin.document.write("<title>Web Site</title>");
myWin.document.write("</head>");
myWin.document.write("<body>");
myWin.document.write("<h1>This is new Web Page</h1>");
myWin.document.write("<h3>Wel Come User</h3>");
myWin.document.write("</body>");
myWin.document.write("</html>");
}
</script></head>
<body><form name="form1">
<input type="button" value="Open Window" onclick="myFunction()">
</form></body></html>
Java Script in URLs
The JavaScript code can be included in 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 following code in URL bar
Javascript: alert(0)
This will show a pop up window of alert box.
If the JavaScript code in a JavaScript: URL contains
multiple statements then these statements must be separated
by semicolons. For example —
Javascript:var t = now Date(); " The time is: " + t;
But for the security reasons modem web browsers are not
allowing to execute' JavaScript:" code in URL.

JavaScript Security
Javascript has several security issues that need widespread 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.
This vulnerability may cause the user data theft, account tampering and
so on.
JavaScript vulnerabilities can be both client-side problems and server-
side as well as hackers are able to steal server-side data and infect the
users with malware. Therefore, server-side JavaScript injection is also a
much more dangerous problem in an application.
• Cross-Site Request Forgery (CSRF) attack is another issue in
Javascript Cross-Site
Request Forgery involves taking over or impersonating a user's browser
session by hijacking the session cookie.
Timer
Using window object it is possible to execute the code at specified time
intervals.
Two functions are supported by window object for handling timing events
and those are –
1. setTimeout
2. setlnterval

(1) setTimeout ( )
This method executes function after waiting for a specified number
of milliseconds.
Syntax
window.setTimeout(function, milliseconds):
function- function to be executed
milliseconds- no of milliseconds before execution take place
The function is only executed once
JavaScript Program to execute timer with setTimeout Method

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Wel Come");
}
</script>
</head>
<body>
<input type="button" value="Open Window"
onclick="setTimeout(myFunction,4000);">
</body>
</html>
Timer Cont..
2.The setInterval() method calls a function or evaluates an
expression at specified intervals(in milliseconds).
JavaScript Program to execute timer with setInterval Method

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
alert("Wel Come");
}
</script>
</head>
<body>
<input type="button" value="Open Window"
onclick="setInterval(myFunction,4000);"> </body>
</html>
Browser location and history
(1) Location
The location object contains information about the current URL.

The location object is part of the window object and is accessed through
the window. location property.
Browser location and history Cont..
Location Object Properties
Sr . Property Description
No

1 hash Sets or returns the anchor part (#) of a URL

2 host Sets or returns the hostname and port number of a URL

3 Sets or returns the hostname of a URL


hostname
4 href Sets or returns the entire URL

5 origin Returns the protocol, hostname and port number of a URL

6 pathname Sets or returns the path name of a URL


7 port Sets or returns the port number of a URL
Browser location and history Cont..
Location Object Properties

Sr.No Property Description


8 protocol Sets or returns the protocol of a URL

9 search Sets or returns the query string part of a URL


Browser location and history Cont..
Location Object Methods

Sr.No Methods Description

1 assign() Loads a new document

2 reload() Reloads the current document

3 replace() Replaces the current document with a new one

4 assign() Loads a new document


JavaScript Program to display the path name of the web page using
window.location object

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script type = "text/javascript">
document.getElementById("demo").innerHTML = "This web page is at
path" +window.location.pathname;;
</script>
</body>
</html>
JavaScript Program to display the protocol name of the web page using
window.location object

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script type = "text/javascript">
document.getElementById("demo").innerHTML = "This web page is using
the protocol= "
+ window.location.protocol;
</script>
</body>
</html>
JavaScript Program to display the URL of current web page using
window.location.href object

<!DOCTYPE html>
<html>

<body>

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

<script type = "text/javascript">

document.getElementById("demo").innerHTML = "This web page is using


the protocol= "+ window.location.href;

</script>

</body>

</html>
JavaScript Program to display the Host name of web page using
window.location.hostname object

<!DOCTYPE html>

<html>

<body>

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

<script type = "text/javascript">

document.getElementById("demo").innerHTML = "This web page is using


the protocol= "+ window.location.hostname;

</script>

</body>

</html>
JavaScript Program to display the Host name of web page using
window.location.hostname object

<!DOCTYPE html>

<html>

<body>

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

<script type = "text/javascript">

document.getElementById("demo").innerHTML = "This web page is using


the protocol= "+ window.location.port;

</script>

</body>

</html>
JavaScript Program to load web page document using
window.location.assign object

<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
• The window. history object contains the browsers
history.
• There are two methods:
• history.back()
• This method load the previous URL in history list.
Same as clicking back in the browser
• history.forward()
This method loads the next URL in the history. Same as clicking
forward in the browser
• 1.history.back()
• method loads the previous URL in the history list.
This is the same as clicking the Back button in the
browser.
JavaScript Program to load previous URL of the current web page using
window.history.back() method

<html>
<head>
<script>
function goBack() {
window.history.back()
}
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
</body>
</html>
Window History Cont..

2.history.forward()
method loads the next URL in the history list.
This is the same as clicking the Forward button in the
browser.
JavaScript Program to load next URL of the current web page using
window.history.forward() method

<html>
<head>
<script>
function goForward() {
window.history.forward()
}
</script>
</head>
<body>
<input type="button" value="Forward" onclick="goForward()">
</body>
</html>

You might also like