You are on page 1of 10

Unit IV: Cookies and Browser Data

Unit IV - Cookies and Browser Data


Basic of Cookies:
A cookie is an amount of information that persists between a server-side and a client-side. A
web browser stores this information at the time of browsing.
A cookie contains the information as a string generally in the form of a name-value pair
separated by semicolons. It maintains the state of a user and remembers the user's information
among all the web pages.
Cookies are a plain text data record of 5 variable-length fields −
Name=Value − Cookies are set and retrieved in the form of key-value pairs
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor
quits the browser.
Domain − The domain name of your site.
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.
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.
Q. State and explain what is a session cookie ? [2 marks]
A session cookie contains information that is stored in a temporary memory location and then
subsequently deleted after the session is completed or the web browser is closed. This cookie
stores information that the user has inputted and tracks the movements of the user within the
website.
A session cookie is also known as transient cookies.

Create Cookie:
<html>
<head><title>Create or Set Cookies Demonstration</title></head>
<body>
<h2>Create or Set Cookies</h2>
<form action="" name="form1">
Name: <input type="text" name="t1"><br><br>
Password : <input type="password" name="t2"><br><br>
<input type="reset" value="Create Now" onclick="newCookie()">
</form>
<script>
with(document.form1){
function newCookie(){
if(t1.value != "" && t2.value != "" ){
document.cookie = "name="+t1.value;
document.cookie = "pass="+t2.value;
alert("Cookies are created.");
}
else{

1
Unit IV: Cookies and Browser Data

alert("Please enter some value");


}
}
}
</script>
</body>
</html>
Read Cookies:
<html><head><title>Read Cookies</title></head>
<body>
<h2>Read Cookies</h2>
<form action="" name="form1">
Name <input type="text" name="t1"><br><br>
Password <input type="text" name="t2"><br> <br>
<input type="button" value="Read Cookies" onclick="readCookie()">
</form>
<script>
with(document.form1){
function readCookie(){
var getCookie = document.cookie.split(";");
console.log("Cookie Values: " +getCookie);
for(var i=0;i<getCookie.length;i++){
var getElements = getCookie[i].split("=");
console.log("Cookie Elements Value: " +getElements);
if(getElements[0].trim() == "studentName"){
t1.value = getElements[1];
}
else if(getElements[0].trim() == "address"){
t2.value = getElements[1];
}
}
}
}
</script></body></html>
Delete Cookies:
<html> <head><title>Delete Cookies</title></head>
<body>
<h2>Delete Cookies</h2>
<form action="" name="form1">
Name <input type="text" name="t1"><br><br>
Password <input type="text" name="t2"><br><br>
<input type="button" value="Delete Cookies" onclick="deleteCookie()">
</form>

2
Unit IV: Cookies and Browser Data

<script>
with(document.form1){
function deleteCookie(){
document.cookie = "name="+t1.value+";expires=Thu, 01 Jan 1980 00:00:01 UTC";
document.cookie = "pass="+t2.value+"expires=Thu, 01 Jan 1980 00:00:01 UTC";
console.log("Cookies Deleted");
} } </script> </body></html>
Setting the expiration date of cookies:
<html> <head><title>Delete Cookies</title></head>
<body>
<h2>Delete Cookies</h2>
<form action="" name="form1">
Name <input type="text" name="t1"><br><br>
Address <input type="text" name="t2"><br><br>
<input type="button" value="Set Expiration Date for Cookies" onclick="setCookie()">
</form>
<script>
with(document.form1){
function setCookie(){
if(t1.value != "" && t2.value != ""){
document.cookie = "name="+t1.value+";expires=Thu, 26 September 2019 01:15:20 UTC";
document.cookie = "pass="+t2.value+"expires=Thu, 26 September 2019 01:15:20 UTC";
console.log("Cookies expiration date has been set");
}
else
{
alert("Please enter some values");
} } }
</script>
</body>
</html>

4.2 Browser: Opening a Window, giving a focus to new window, window position, closing
a window:
The open() method opens a new browser window, or a new tab, depending on your browser
settings and the parameter values.
Example
<html>
<head><title>Window open() method</title></head>
<body>
<h2>Window open() method</h2>
<input type="button" value="Open Window" onclick="windowOpen()">
<script>

3
Unit IV: Cookies and Browser Data

var win;
function windowOpen() {
win = window.open("","_blank", "resizable=no, left=200, top=400,width=400, height=450");
}
</script>
</body>
</html>
The focus() method sets focus to the current window.
The blur() method removes focus from the current window.
The close() method closes the current window.
Example:
<html><head><title>Window open(), close(), blur() and focus() method</title></head>
<body>
<h2>Windows open, blur, focus, close and set position </h2>
<input type="button" value="Open Window" onclick="windowOpen()">
<input type="button" value="Blur Window" onclick="windowBlur()">
<input type="button" value="Focus Window" onclick="windowFocus()">
<input type="button" value="Close Window" onclick="windowClose()">
<script>
var win;
function windowOpen() {
win = window.open("","_blank", "width=400, height=450");
}
function windowBlur() {
win.blur();
}
function windowFocus() {
win.focus();
}
function windowClose(){
win.close();
}
</script></body></html>

Changing the content of window:


<html>
<head><title>Changing contents of window</title></head>
<body>
<h1 id="show" onmouseover="changeContent()" onmouseout = "orignalContent()">
This is HTML content</h1>
<script>
function changeContent(){
document.getElementById("show").innerHTML = "This is JavaScript content."

4
Unit IV: Cookies and Browser Data

}
function orignalContent(){
document.getElementById("show").innerHTML = "This is HTML content."
} </script> </body> </html>
Scrolling a Webpage:
<html>
<head><title>Scrolling a webpage.</title>
<style>
body{ width: 2000px; height: 2000px; }
</style>
</head>
<body>
<h2>Click to button for Scrolling this window</h2>
<input type="submit" value="Scroll window" onclick="scrollNow()">
</body>
<script>
function scrollNow(){
scrollTo(1500,1500);
}
</script>
</html>

Multiple Windows at Once:


<html>
<head><title>Open Window</title></head>
<body>
<form action="" name="form1">
<input type="button" value="Open Window" onclick="openWindow()">
</form>
<script>
with (document.form1){
function openWindow(){
window.open("https://www.google.com","","width=300,height=200", "1");
window.open("https://www.facebook.com","","left=300, top=5, width=300, height=200", "2");
window.open("https://www.twitter.com","","left=700, top=5, width=300, height=200", "3");
}
}
</script>
</body>
</html>

5
Unit IV: Cookies and Browser Data

Creating a Webpage in New Window:


<html>
<head><title>Open Window</title></head>
<body>
<form action="" name="form1">
<input type="button" value="Open Window" onclick="openWindow()">
</form>
<script>
with (document.form1){
var openWin;
function openWindow(){
openWin = window.open("","_blank", "width=300, height=200", "1");
openWin.document.write("<html>");
openWin.document.write("<head>");
openWin.document.write("<title>");
openWin.document.write("My Web Page");
openWin.document.write("</title>");
openWin.document.write("</head>");
openWin.document.write("<body>");
openWin.document.write("<h1>Webpage is Created</h1>");
openWin.document.write("<//body>");
openWin.document.write("</html>");
}
}
</script>
</body>
</html>

Javascript in URLs:
JavaScript in URLs Another way that JavaScript code can be included on the client side is in a
URL following the javascript: 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.
A JavaScript URL will contain JavaScript statements that perform actions but return no
value.
For example: javascript:alert("Hello World!")
javascript: URLs can also be used in other contexts. You might use one as the target of a
hypertext link, for example. Then when the user clicks on the link, the specified JavaScript code
will be executed. Or, if you specify a javascript: URL as the value of the ACTION attribute of a
tag, then the JavaScript code in the URL will be executed when the user submits the form.
For security reasons the recent browsers are not allowing to execute the javascript code in
URLs.

6
Unit IV: Cookies and Browser Data

JavaScript Security:
One of the most common JavaScript security vulnerabilities are 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. XSS vulnerabilities can exist when browser or application authors
fail to implement the same origin policy and can be prevented by following correct development
techniques. If XSS vulnerabilities aren’t remediated, they can result in user data theft, account
tampering, malware spreading or remote control over a user’s browser.

Another common JavaScript security vulnerability is Cross-Site Request Forgery (CSRF).


Cross-Site Request Forgery vulnerabilities allow attackers to manipulate victims’ browsers to
take unintended actions on other sites. This is possible when target sites authenticate requests
solely using cookies and attackers are able to send requests carrying users’ cookies. This
JavaScript security issue can lead to account tampering, data theft, fraud and more. Both
Cross-Site Scripting and Cross-Site Request Forgery vulnerabilities exist in the application layer
and require that correct development techniques are followed in order to be avoided.

There are a variety of other common JavaScript security issues that can increase risks for
users. These issues include improper client-server trust relationships, vulnerabilities in browser
and browser plugin code, and incorrect implementation of sandboxing or same origin policy.
And for Node.js-based server side applications, there may be many other security
vulnerabilities, including SQL Injection, Command Injection, and others. The only way for
organizations to avoid these JavaScript security risks is to develop and source applications that
are free of JavaScript security vulnerabilities. Many organizations use JavaScript security
analyzers to test for and remediate these vulnerabilities.

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. For example, you can use timers to change
the advertisement banners on your website at regular intervals, or display a real-time clock, etc.
There are two timer functions in JavaScript: setTimeout() and setInterval().

7
Unit IV: Cookies and Browser Data

1. The setTimeout() Method:


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.

<html>
<head>
<meta charset="utf-8">
<title>JavaScript Execute a Function after Some Time</title>
</head>
<body>
<script>
function myFunction() {
alert('Hello World!');
}
</script>
<button onclick="setTimeout(myFunction, 2000)">Click Me</button>
</body>
</html>
The above example will display an alert message after 2 seconds on click of a button.

2. The setInterval() Method


The setInterval() method repeats a given function at every given time-interval.
window.setInterval(function, milliseconds);
The window.setInterval() method can be written without the window prefix.
The first parameter is the function to be executed.
The second parameter indicates the length of the time-interval between each execution.
<html>
<body>
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
setInterval(function(){ alert("Hello"); }, 3000);
}
</script>
</body>
</html>

8
Unit IV: Cookies and Browser Data

Browser Location and History:


Location:
Window Location
The window.location object can be written without the window prefix.
Some examples:
window.location.href returns the href (URL) of the current page
window.location.hostname returns the domain name of the 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 Href
The window.location.href property returns the URL of the current page.
Example
Display the href (URL) of the current page:
document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;

Window Location Hostname


The window.location.hostname property returns the name of the internet host (of the current
page).
Example
Display the name of the host:
document.getElementById("demo").innerHTML =
"Page hostname is " + window.location.hostname;

Window Location Pathname


The window.location.pathname property returns the pathname of the current page.
Example
Display the path name of the current URL:
document.getElementById("demo").innerHTML =
"Page path is " + window.location.pathname;

Window Location Protocol


The window.location.protocol property returns the web protocol of the page.
Example
Display the web protocol:
document.getElementById("demo").innerHTML =
"Page protocol is " + window.location.protocol;

9
Unit IV: Cookies and Browser Data

Window 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.
Some methods:
history.back() - same as clicking back in the browser
history.forward() - same as clicking forward in the browser
Window History Back
The history.back() method loads the previous URL in the history list.
This is the same as clicking the Back button in the browser.
Example
Create a back button on a page:
<html>
<head>
<script>
function goBack() {
window.history.back()
}
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
</body>
</html>

Window History Forward


The history.forward() method loads the next URL in the history list.
This is the same as clicking the Forward button in the browser.
Example
Create a forward button on a page:
<html>
<head>
<script>
function goForward() {
window.history.forward()
}
</script>
</head>
<body>
<input type="button" value="Forward" onclick="goForward()">
</body>
</html>

10

You might also like