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

Chapter 4 Cookies and Browser Data

Uploaded by

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

Chapter 4 Cookies and Browser Data

Uploaded by

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

Chapter 4

Cookies and Browser Data


Cookie:
• 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
Cookie Cont.:
• 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.
• None of the examples below will work if your
browser has local cookies support turned off.
Creating Cookie :
• JavaScript can create, read, and delete cookies with
the document.cookie property.
• With JavaScript, a cookie can be created like this:
document.cookie = "username=AAA";
• You can also add an expiry date (in UTC time). By
default, the cookie is deleted when the browser is closed:
document.cookie = "username=AAA; 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 Doe; expires=Thu,
18 Dec 2013 12:00:00 UTC; path=/";
Reading Cookie :
• With JavaScript, cookies can be read like this:
var x = document.cookie;
• document.cookie will return all cookies in one string
much like:
cookie1=value; cookie2=value; cookie3=value;
• Change a Cookie:
• With JavaScript, you can change a cookie the same
way as you create it:
document.cookie = "username=John Smith;
expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
• The old cookie is overwritten
Deleting Cookie :
• Deleting a cookie is very simple.
• You don't have to specify a cookie value when you
delete a cookie.
• Just set the expires parameter to a passed date:
document.cookie = "username=; expires=Thu, 01 Jan
1970 00:00:00 UTC; path=/;";
• 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.
The Cookie String:
• The document.cookie property looks like a normal text
string. But it is not.
• Even if you write a whole cookie string to
document.cookie, when you read it out again, you can
only see the name-value pair of it.
• If you set a new cookie, older cookies are not
overwritten. The new cookie is added to
document.cookie, so if you read document.cookie
again you will get something like:
cookie1 = value; cookie2 = value;
• If you want to find the value of one specified cookie,
you must write a JavaScript function that searches for
the cookie value in the cookie string.
Cookie 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
Function to set Cookie:
• 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);
}
}
}
Explanation:
• 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:
Browser Object Model (BOM):
• 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.
The Window Object:
• 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");
The Window Size:
• Two properties can be used to determine the size of the browser
window.
• Both properties return the sizes in pixels:
• window.innerHeight - Inner height of browser window (in pixels)
• 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
The Window Size:
<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>
Opening Multiple tabs:
• 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>
Closing a Window:
<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>
Getting a focus to new Window:
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 contents of a 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 the page of a Window:
• 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>
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
Window 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
Window Location:
<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>
Window Location:
<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:
 navigator.cookieEnabled: returns true if cookies are enabled,
otherwise false
 navigator.appName:returns the application name of the browser
 navigator.appCodeName: returns application code name of
browser
 navigator.product: returns product name of the browser engine
 navigator.appVersion:returns version information about the
browser
Timers
• 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
The setTimeout() and setInterval() are both methods of the HTML
DOM Window object.
setTimeOut()
window.setTimeout(function, milliseconds);
• The window.setTimeout() method can be written without the
window prefix.
• The first parameter is a function to be executed.

• The second parameter indicates the number of milliseconds


before execution.
Sample Program
<html>
<body>
<p>Wait 3 seconds, and the page will alert "Hello".</p>
<button onclick="setTimeout(myFunction, 3000);">Try
it</button>
<script>
function myFunction() {
alert('Hello');
}
</script>
</body>
</html>
How to Stop the Execution?
• The clearTimeout() method stops the execution of the
function specified in setTimeout().

window.clearTimeout(timeoutVariable)
• The window.clearTimeout() method can be written without
the window prefix.

• The clearTimeout() method uses the variable returned from


setTimeout():
myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);
Sample Program
<html>
<body>
<p>Click "Try it". Wait 3 seconds. The page will alert "Hello".</p>
<p>Click "Stop" to prevent the first function to execute.</p>
<button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button>
<button onclick="clearTimeout(myVar)">Stop it</button>
<script>
function myFunction() {
alert("Hello");
}
</script>
</body>
</html>

You might also like