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

CSS CH-4 Updated

Uploaded by

dnyvlogs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

CSS CH-4 Updated

Uploaded by

dnyvlogs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Cookies and Browser Data

Cookies:
A cookie is a small text file that a web site saves on your PC, mobile phone or other device, containing
information about your browsing on that site.
Cookies are necessary to facilitate browsing and make it more convenient; they do not harm your
computer.

Why are cookies used on this website?


Cookies are an essential part of how our website operates. The main purpose of our cookies is to
improve your browsing experience.
For example, to remember your preferences (language, country, etc.) during browsing and on future
visits.
The information collected in cookies also enables us to improve our website, for example, by
estimating user numbers and ways users use the site, adapting the site to individual user's interests,
speeding up searches, etc.
Sometimes, if we have obtained your consent(permission), we can use cookies, tags or other similar
instruments to obtain information that enables us to show you advertising based on your navigation
habits on our own web site, those of other suppliers or in other ways.

Basics of Cookies
 Cookies is a small piece of data stored in a file on your computer.
 The information present in the cookies is accessed by the web browser
A cookie contains the information as a string generally in the form of a name-value pair
separated by semi-colons.
 It maintains the state of a user and remembers the user's information among all the web
pages.
 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

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

 How Cookies Works?


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 to
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.

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.

There are two types of cookies: Session cookies and persistent cookies
Session Cookies : Session cookies is a cookie that remains in temporary memory only
while user is reading and navigating the web site. The cookie is automatically deleted
when the user exits the browser application.

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 date has been reached; then it is deleted.

Creating Cookies
JavaScript can create, read or delete a cookie using document.cookie property
The simplest way to create a cookie is to assign a string value to the document.cookie object,
which looks like this.
document.cookie = "key1 = value1;key2 = value2;expires = date";

document.cookie = "username=Spc";

Here the expires attribute is optional.


If you provide this attribute with a valid date or time, then the cookie will expire on a given date
or time and thereafter, the cookies' value will not be accessible.

Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may
want to use the JavaScript escape() function to encode the value before storing it in the cookie. If
you do this, you will also have to use the corresponding unescape() function when you read the
cookie value.

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

Example Write a JavaScript for creating a cookie for the user name.

<html>
<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>

Now your machine has a cookie called name. You can set multiple cookies using multiple key =
value pairs separated by comma.

 Reading a Cookie Value

It is a common practice to create a cookie and then read the value of the created cookie.
The document.cookie string will keep a list of NAME=VALUE pairs separated by semicolons, name
is the name of a cookie and value is its string value.
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 take all the characters to the left of
the= and store them into array [0].
Next the split() method takes all the characters from the right of the = up to semicolon ( ; ) but not
Including the semicolon, and assign those characters to array[1]
Thus we can obtain the name value pair in array[0] and array[1] respectively.

Following example illustrates how to read the cookies value.

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

<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 following button and see the result:</p>
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form>
</body>
</html>

Note − There may be some other cookies already set on your machine. The above code will display
all the cookies set on your machine.

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

Setting Cookies Expiry Date


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.
Example
Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.
<html>
<head>
<script type = "text/javascript">

function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(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>

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

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.
Example
Try the following example. It illustrates 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.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>

4.2 Browser

Opening a Window

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

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


For that purpose the window object is used.
This window object has various useful properties and methods.
The window.open() method is used to open a new browser window or a new tab depending on
the browser setting and the parameter values.

Syntax
Window.open(URL,name,style)

URL Optional. Specifies the URL of the 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

style Optional. A comma-separated list of items, no whitespaces. The following values are
supported:

fullscreen=yes|no|1|0 Whether or not to display the browser in full-


screen mode. Default is no.

height=pixels The height of the window. Min. value is 100

left=pixels The left position of the window. Negative values


not allowed

menubar=yes|no|1|0 Whether or not to display the menu bar

resizable=yes|no|1|0 Whether or not the window is resizable.

scrollbars=yes|no|1|0 Whether or not to display scroll bars. IE, Firefox


& Opera only

status=yes|no|1|0 Whether or not to add a status bar

titlebar=yes|no|1|0 Whether or not to display the title bar.

toolbar=yes|no|1|0 Whether or not to display the browser toolbar.

top=pixels The top position of the window. Negative values


not allowed

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

width=pixels The width of the window. Min. value is 100

Example 1: Open an about:blank page in a new window/tab

<!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

Example 2:
Replace the current window with a new window:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to put the new window in the current window.</p>

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

<script>
function myFunction() {
var myWindow = window.open("", "_self");
myWindow.document.write("<p>I replaced the current window.</p>");
}
</script>

</body>
</html>

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

Example 3: Open Specified URL

<!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://spccomputeracademy.business.site/");
}
</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.

<!DOCTYPE html>
<html>
<body>

<p>Setting position of window.</p>

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

<script>
function myFunction() {
window.open("", "", "left=200,top=100,width=600,height=600");
}
</script>

</body>
</html>

4.2.4 Changing the content of window


By writing some text to the newly created window we can change content of window

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

<html>
<body>
<p>Click the button to open a new tab </p>
<button onclick="NewTab()">
Open Window
</button>
<script>
function NewTab() {
var mywin=window.open("","","width=200,height=200")
mywin.document.write("<p>This line is written in current window</p>")
}
</script>
</body>
</html>

4.2.5 Closing a Window

The most simple operation about the window is to close it. It can be closed using the function
close()

<!DOCTYPE html>
<html>
<body>

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


<button onclick="closeWin()">Close "myWindow"</button>

<script>
var myWindow;

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

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

</body>
</html>

4.2.6 Multiple Window at a Glance


 It is possible to open up multiple windows at a time.

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

 It is simple to open multiple windows. Using Open() method in a loop.

Example

<html>
<body>
<p>Click the button to open a new tab </p>
<button onclick="NewTab()">Open Window</button>
<script>
function NewTab() {
for(i=0;i<5;i++)

{
var mywin=window.open("","","width=100,height=100")}
}
</script>
</body>
</html>

Timers

setTimeout( )
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Execute a Function after Some Time</title>
</head>
<body>
<script type="text/JavaScript">
function myFunction()
{
alert('Hello World!');
}
</script>

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

<button onclick="setTimeout(myFunction, 2000)">Click Me</button>


<p><strong>Note:</strong> Alert popup will be displayed 2 seconds after clicking the
button.</p>
</body>
</html>

scrollTo()
<html>
<head>

<script type = "text/javascript">


function scrollwindow()
{
window.scrollTo(0,200);
}

</script>

</head>
<body>

<p>click to scroll</p>
<input type="button" value="Scroll Window" onclick="scrollwindow()">
<p>A</p>

<br><br><br><br><br><br>

<p>B</p>

<br><br><br><br><br><br>

<p>C</p>

<br><br><br><br><br><br>

<p>D</p>

<br><br><br><br><br><br>

<p>E</p>

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

<br><br><br><br><br><br><br><br>

<P> ------------ Window Scrolled</p>


</body>
</html>

BROWSER LOCATION AND HISTORY

1. window.location.pathname :
Gives complete path at which the web page is located.
2. window.location.hostname:
Gives name of host on which the webpage is running. It gives domain name
3. window.location.protocol:
Gives the protocol used for the webpage. Such as HTTP, HTTPS

Q Write a JavaScript code to get a pathname.

<html>
<head>
<script type="text/javascript">
function display()
{
document.getElementById("ID").innerHTML = "This web page is at path:" +
window.location.pathname;
}
</script>
</head>
<body>
<input type="button" value="GetPath" onclick="display()">
<p id="ID"></p>

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

</body>
</html>

Q Write a JavaScript code to get the protocol.


<html>
<head>
<script type="text/javascript">
function display()
{
document.getElementById("ID").innerHTML = "The protocol of Web Page is:" +
window.location.protocol;
}
</script>
</head>
<body>
<p>Click the button to get the Protocol</p>
<input type="button" value="GetProtocol" onclick="display()">
<p id="ID"></p>
</body>
</html>

Q Write a JavaScript code to get the hostname of webpage.

<html>
<head>
<script type="text/javascript">
function display()
{
document.getElementById("ID").innerHTML = "The hostname of Web Page is:" +
window.location.hostname;
}
</script>
</head>
<body>
<input type="button" value="GetHost" onclick="display()">
<p id="ID"></p>
</body>
</html>

History
<html>
<head>
<script type="text/javascript">
function previous()

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)


Cookies and Browser Data

{
window.history.back();
}
function next()
{
window.history.forward();
}
</script>
</head>
<body>

<input type="button" value="Previous" onclick="previous()">


<input type="button" value="Next" onclick="next()">

</body>
</html>

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)

You might also like