0% found this document useful (0 votes)
89 views15 pages

Chapter 4 Cookie

This document discusses cookies and the browser object model in JavaScript. It provides information on: - How cookies work and their basic structure of name-value pairs stored in text files on a user's computer. - Methods for creating, reading, deleting, and setting expiration dates for cookies using the document.cookie property. - The browser object model (BOM) which allows JavaScript to interact with the browser, and the window object model which represents the browser window. - Properties and methods of the window object for getting window sizes, opening new windows, and changing window content.

Uploaded by

damayanti
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)
89 views15 pages

Chapter 4 Cookie

This document discusses cookies and the browser object model in JavaScript. It provides information on: - How cookies work and their basic structure of name-value pairs stored in text files on a user's computer. - Methods for creating, reading, deleting, and setting expiration dates for cookies using the document.cookie property. - The browser object model (BOM) which allows JavaScript to interact with the browser, and the window object model which represents the browser window. - Properties and methods of the window object for getting window sizes, opening new windows, and changing window content.

Uploaded by

damayanti
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/ 15

Chapter 4: Cookies and Browser Data

4.1Cookies- basic of cookies, reading a cookie value, writing a cookie value

Basic of Cookies

• Cookies are data, stored in small text files, on your computer.

• When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.

• Cookies were invented to solve the problem "how to remember information about the user":

• When a user visits a web page, his/her name can be stored in a cookie.

• Next time the user visits the page, the cookie "remembers" his/her name.

• Cookies are saved in name-value pairs like: username = AAA Eg: username = John Doe

• When a browser requests a web page from a server, cookies belonging to the page are added to the request.

• This way the server gets the necessary data to "remember" information about users.

Contents of Cookie

Cookies are a plain text data record of 5 variable-length fields −


1. Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
2. Domain − The domain name of your site.
3. Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory
or page.
4. Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no
such restriction exists.
5. Name=Value − Cookies are set and retrieved in the form of key-value pairs

4.2 Creating a cookie, deleting a cookie, setting expiration date of cookies

Creating a cookie
- JavaScript can create, read, and delete cookies with the document.cookie property.
Eg : document.cookie = "username=John Doe";
- You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed.
Eg : document.cookie = "username=John Doe; 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.
Eg : document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";<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>

reading a cookie
– Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie.
– 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.
– document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;
Ex: Program to display all contents of a 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 following button and see the result:</p>
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form>
</body>
</html>

deleting a cookie
- Sometimes you will want to delete a cookie.
- You don't have to specify a cookie value when you delete a cookie
- To do this, you just need to set the expiry date to a time in the past.
- You should define the cookie path to ensure that you delete the right cookie. Some browsers will not let you delete a cookie if you don't
specify the path
-
function DeleteCookie()
{
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 );
}

setting expiration date of cookies


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 );
}

Example: In this example, we will create a cookie that stores the name of a visitor.
• The first time a visitor arrives to the web page, he/she will be asked to fill in his/her name. The name is then stored in a cookie.
• The next time the visitor arrives at the same page, he/she will get a welcome message.
• For the example we will create 3 JavaScript functions:
• A function to set a cookie value
• A function to get a cookie value
• A function to check a cookie value

• First, we create a function that stores the name of the visitor in a cookie variable:
Ex: function setCookie(cname, cvalue, exdays)
{
var d= new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires= "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
Explanation:
• The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until
the cookie should expire (exdays).
• The function sets a cookie by adding together the cookiename, the
cookie value, and the expires string.

Function to get Cookie:


function getCookie(cname)
{
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++)
{
var c = ca[i];
while (c.charAt(0) == ' ')
{
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}

Explanation:
• Take the cookiename as parameter (cname).
• Create a variable (name) with the text to search for (cname + "=").
• Decode the cookie string, to handle cookies with special characters, e.g. '$'
• Split document.cookie on semicolons into an array called ca (ca = decodedCookie.split(';')).
• Loop through the ca array (i = 0; i < ca.length; i++), and read out each value c = ca[i]).
• If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length, c.length).
• If the cookie is not found, return "".

Function to check Cookie:


function checkCookie()
{
var username = getCookie("username");
if (username != "")
{
alert("Welcome again " + username);
}
else
{
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}

• Last, we create the function that checks if a cookie is set.


• If the cookie is set it will display a greeting.
 If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by
calling the setCookie function:

4.3 Browser-opening a window, giving the new window focus, window position
4.4 changing the content of window, closing a window, scrolling a web page, multiple windows at once

Browser Object Model


• The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
• There are no official standards for the Browser Object Model.
• Since modern browsers have implemented (almost) the same methods and properties for JavaScript interactivity, it is often referred to,
as methods and properties of the BOM.

Window Object Model


• The window object is supported by all browsers. It represents the browser's window.
• All global JavaScript objects, functions, and variables automatically become members of the window object.
• Global variables are properties of the window object.
• Global functions are methods of the window object.
• Even the document object (of the HTML DOM) is a property of the window object:
window.document.getElementById("header"); is the same as: document.getElementById("header");
• Two properties can be used to determine the size of the browser window. Both properties return the sizes in pixels:
1. window.innerHeight - Inner height of browser window (in pixels)
2. window.innerWidth - Inner width of browser window (in pixels)
• The browser window (the browser viewport) is NOT including toolbars and scrollbars.
• For IE 5,6,7,8
document.documentElement.clientHeight
document.documentElement.clientWidth
or document.body.clientHeight document.body.clientWidth

<html>
<body>
<p id="demo"></p>
<script>
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
</script>
</body>
</html>
Other Window Methods
• window.open() - The open() method opens a new browser window, or a new tab, depending on your browser settings and the parameter
values.
• window.close() - close the current window
• window.moveTo() - move the current window
• window.resizeTo() - resize the current window

Opening a Window in new browser tab:


• Open "www.w3schools.com" in a new browser tab
<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>

Opening a blank page in new Window:


• Open an about:blank page in a new window/tab:
<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>
Open Multiple tabs:
<html>
<body>
<p>Click the button to open multiple tabs.</p>
<button onclick="myFunction()">Open Windows</button>
<script>
function myFunction() {
window.open("http://www.google.com/");
window.open("https://www.w3schools.com/");
}
</script>
</body>
</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>

Giving the new window focus


The focus() method sets focus to the current window.
<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>

Changing Content of Window


• The replace() method replaces the current document with a new one.
• The replace() removes the URL of the current document from the document history, meaning that it is not possible to use the "back"
button to navigate back to the original document.
Ex:
<html>
<body>
<button onclick="myFunction()">Replace document</button>
<script>
function myFunction() {
location.replace("https://www.w3schools.com")
}
</script>
</body>
</html>

Scrolling Webpage
• The scrollTo() method scrolls the document to the specified coordinates.
• The scrollBy() method used to scroll a specified distance multiple times.
<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>

4.5 creating a web page in new window, javascript in URLs, javascript security, timers, browser location and history

- JavaScript is designed as an open scripting language. It is not intended to replace proper security measures, and should never be used in place
of proper encryption.
- JavaScript has its own security model, but this is not designed to protect the Web site owner or the data passed between the browser and the
server.
- The security model is designed to protect the user from malicious Web sites, and as a result, it enforces strict limits on what the page author is
allowed to do. They may have control over their own page inside the browser, but that is where their abilities end.
- JavaScript cannot read or write files on users', though they can cause the browser to load remote pages and resources like scripts or images,
which the browser may choose to cache locally. They cannot create files on the server (except by communicating with a server side script that
creates files for them). The only thing they can store on the user's computer are cookies.
- They are allowed to interact with other pages in a frameset, if those frames originate from the same Web site, but not if they originate from
another Web site. Some browsers will even treat different port numbers on the same server as a different Web site.
- JavaScript cannot be used to set the value attribute of a file input, and will not be allowed to use them to upload files without permission.
- JavaScript cannot read what locations a user has visited by reading them from the location object, although it can tell the browser to jump
back or forward any number of steps through the browser history. It cannot see what other Web pages the user has open.
- JavaScript cannot access the cookies or variables from other sites.
- It cannot see when the user interacts with other programs, or other parts of the browser window.
- It cannot open windows out of sight from the user or too small for the user to see, and in most browsers, it cannot close windows that it did not
open.
- Most people who want to know about security with JavaScript are interested in producing password protected pages or sending encrypted data
to or from the user's computer.
- For true security, use SSL/TLS (HTTPS) and put all of your checks on the server. You could also use a security lockout if too many false
attempts are made, preventing brute force cracks. JavaScript cannot replace this functionality.

- There are 2 ways of protecting webpage:


1. Disabling right click: The source code of a web page can be viewed by clicking right mouse button on the webpage. Anyone can see the
source code of a webpage which is not safe. We can hide the code by disabling right mouse click on webpage. Hiding source
code is nothing but protecting the source code by viewing other users.
JavaScript for Disabling right click
<script>
document.addEventListener('contextmenu',event=>event.preventDefault())
</script>

2. Concealing email address:It means hiding email address from unauthorized user. It is possible with the use of JavaScript.
JavaScript for concealing email address
function (user_email)
{
varavg, splitted, part1, part2;
splitted = user_email.split("@");
part1 = splitted[0];
avg = part1.length / 2;
part1 = part1.substring(0, (part1.length - avg));
part2 = splitted[1];
alert(part1 + "...@" + part2);
};
Timers
- A timer is a function that enables us to execute a function at a particular time.
- Using timers you can delay the execution of code so that it does not get done at the exact moment an event is triggered or the page is loaded.
- 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
setTimeout(function, milliseconds):Executes a function, after waiting a specified number of milliseconds.
setInterval(function, milliseconds):Same as setTimeout(), but repeats the execution of the function continuously.
-
setTimeout()
-The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
- Syntax :setTimeout(function, milliseconds, param1, param2, ...)
Here, function : The function that will be executed
milliseconds :The number of milliseconds to wait before executing the code.
If omitted, the value 0 is used
param1, param2, ...: Additional parameters to pass to the function
- Example:myVar = setTimeout(alertFunc, 3000);
setInterval()
- This 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
- Syntax:setInterval(function, milliseconds, param1, param2, ...)
Here, function : The function that will be executed
milliseconds :The intervals (in milliseconds) on how often to execute the
code. If the value is less than 10, the value 10 is used
param1, param2, ...: Additional parameters to pass to the function
-Example :myVar = setInterval(alertFunc, 3000);
Window Screen
• The window.screen object contains information about the user's screen.
• The window.screen object can be written without the window prefix.
• Properties:
– screen.width
– screen.height
– screen.availWidth
– screen.availHeight
– screen.colorDepth: returns the number of bits used to display one color.
– screen.pixelDepth: returns the pixel depth of the screen

<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Screen width is " + screen.width;
</script>
</body>
</html>

Window Location
• The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.
• The window.location object can be written without the window prefix.
Ex:
• window.location.href: returns the href (URL) of the current page
• window.location.hostname: returns the domain name of 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
<html>
<body>
<h2>JavaScript</h2>
<h3>The window.location object</h3>
<p id="demo"></p>
<script> document.getElementById("demo").innerHTML =
"The full URL of this page is:<br>" + window.location.href;
</script>
</body>
</html>

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


• The window.history object can be written without the window prefix.
• To protect the privacy of the users, there are limitations to how JavaScript can access this object.
Methods:
 history.back() - same as clicking back in the browser
 history.forward() - same as clicking forward in the browser

Window Navigator:
 The window.navigator object contains information about the visitor's browser.
 The window.navigator object can be written without the window prefix.
 Properties:
1. navigator.cookieEnabled: returns true if cookies are enabled, otherwise false
2. navigator.appName:returns the application name of the browser
3. navigator.appCodeName: returns application code name of browser
4. navigator.product: returns product name of the browser engine
5. navigator.appVersion:returns version information about the browser
6. navigator.userAgent: returns the user-agent header sent by the browser to the server
7. navigator.platform:returns the browser platform (operating system):
8. navigator.language: returns the browser's language:
9. navigator.online: returns true if the browser is online:
10. navigator.javaEnabled():method returns true if Java is enabled

You might also like