Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
106 views

CSS Chapter 4 Notes

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

CSS Chapter 4 Notes

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

Client Side Scripting Language : JavaScript

Unit 4 : Cookies and Browser Data


4.1 Cookies – Basic of cookies,
Creating a cookies,
Reading a cookie value,
Writing a cookie value,
Deleting a cookies,
Setting the expiration date of cookie
4.2 Browser – Opening a window,
Giving the new window focus,
Window position,
Changing the content of window,
Closing a window,
Scrolling a web page,
Multiple windows at once,
Creating a web page in new window,
JavaScript in URL’s,
JavaScript security,
Timers,
Browser location and history22519]

Prof. Pathan F. S 1 Jamia Polytechnic (0366)


Computer Dept. Akkalkuwa
Client Side Scripting Language : JavaScript
Cookies – Basic of cookies:
A cookie is small amount of information that persists between a server and a client. 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 semi-colons. It maintains the state of a user and remembers the user's information
among all the web pages.
Cookies in JavaScript is a set of data stored in the browser that is fetched whenever a web
page is loaded, and the content of this cookie is used to reload the web page whenever there is a
connectivity issue or the server is not reachable.
Whenever we make any request to the server it sends some data to the user browsers in the
form of a cookie. The browser can accept the cookie.
Cookies are a plain text data record of 5 variable-length fields
 Expires − the date the cookie will expire. If this is blank, the cookie will expire when the
visitor quits the browser. Maximum age of cookies in second (e.g., 60*60*24*365)
 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.
 Name=Value − Cookies are set and retrieved in the form of key-value pairs.
Types of web cookies:
All web cookies are not created equal nor do they all serve the same functions. Depending
on the type there are 3 main types of cookies:
SESSION COOKIES
These are temporary web cookies that are only present as long as your web browser stays
open or your session is active. Once you close your browser or your browser session becomes
inactive (after a period of time), these cookies are removed from your device.
PERSISTENT COOKIES
Persistent (Permanent) cookies last longer than session cookies. The website you visit
creates this cookie and attaches an expiration date to them.
THIRD-PARTY COOKIES
These cookies are created by a website you‟re not visiting. These cookies are usually
created by advertisers and associate you to a website where you clicked on an ad.
Third-party cookies gather data about your browsing habits. They allow advertisers to track you
across multiple websites and serve ads to you wherever you go across the internet.
Creating a Cookie :
Javascript can create, read and delete cookies with the document.cookie property.
The simplest way to create a cookie is to assign a string value to the document.cookie property.
document.cookie = "username=Firozkhan";
You can also add an expiry date.
document.cookie = "username=Firozkhan; expires=Thu, 18 Dec 2023 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie belongs to.
document.cookie = "username=Firozkhan; expires=Thu,18 Dec 2023 12:00:00 UTC; path=/";

Prof. Pathan F. S 2 Jamia Polytechnic (0366)


Computer Dept. Akkalkuwa
Client Side Scripting Language : JavaScript
Function to creating Cookie :
<script>
function setCookie() {
var name = document.getElementById('person').value
document.cookie = "name=" + name + ";"
alert("Cookie Created")
}
</script>
Reading a cookie value:
Reading a cookie is just as simple, 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.
Function to read cookie value :
function readCookie()
{
var cookie = document.cookie
var panel = document.getElementById('panel')
if (cookie == "")
panel.innerHTML = "Cookie not found"
else
panel.innerHTML = cookie
}
Using split() function the string of cookie is break into key and values. The split() finds the „=‟
character in cookie and then take all the characters to the left of the „=‟ sign and store them into
arrays.
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);
}
}
Example 4.1 Reading and Writing a Cookie.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exp 10</title>
<h3>Creating and Reading cookie</h3>
<script>
function setCookie() {
var name = document.getElementById('person').value
document.cookie = "name=" + name + ";"
Prof. Pathan F. S 3 Jamia Polytechnic (0366)
Computer Dept. Akkalkuwa
Client Side Scripting Language : JavaScript
alert("Cookie Created")
}
function readCookie() {
var cookie = document.cookie
var panel = document.getElementById('panel')
if (cookie == "")
panel.innerHTML = "Cookie not found"
else
panel.innerHTML = cookie
}
</script>
</head>
<body>
<form name="myForm">
Enter your name <input type="text" id="person" /><br />
<input type="button" value="Set Cookie" onclick="setCookie()" />
<input type="button" value="Read Cookie" onclick="readCookie()" />
<p id="panel"></p>
</form>
<!-- Creating a persistent cookies -->
<script>
var date = new Date();
var days=2;
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = date.toGMTString();
document.cookie = "user=Jamia; expires="+ expires + ";"
alert("Cookie Created\n"+document.cookie);
</script>
</body>
</html>
Output:

Deleting cookies:
If the cookies are temporary then it will be deleted automatically when the browser session ends
or its expiration date is reached. If we went to delete the cookie without closing the browser, we
must update the expiry date to the past manually. Hence by setting previous expiry date we can
delete cookies.
document.cookie = "username=value; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Prof. Pathan F. S 4 Jamia Polytechnic (0366)


Computer Dept. Akkalkuwa
Client Side Scripting Language : JavaScript
Function to delete cookie value:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exp 10</title>
<h3>Creating and Reading cookie</h3>
<script>
function deleteCookie()
{
var cookie_value = username.value;
document.cookie="User name ="+cookie_value+";expires =Thu, 01 Jan 2001 00:00:01 GMT";
alert("Cookie is deleted");
}
</script>
</head>
<body>
<form name="myForm">
Enter Username : <input type="text" id="username">
<input type="button" value="Delete Cookie" onclick="deleteCookie()">
</form>
</body>
</html>
Output :

Setting the expiration date of cookie:


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. These can be done by setting the „expires‟
attribute date and time.
getMonth() – returns the month of the current date object.
setMonth() – set the month to the current date object.
toUTCString() – formats the date in the standard format to set the expiration date of the cookie.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exp 10</title>
<h3>Creating and Reading cookie</h3>
<script>
function changedate()
{
var now = new Date();

Prof. Pathan F. S 5 Jamia Polytechnic (0366)


Computer Dept. Akkalkuwa
Client Side Scripting Language : JavaScript
now.setMonth(now.getMonth+1);
var cookie_value = username.value;
document.cookie="Username ="+cookie_value+";expires ="+now.toUTCString();
alert("Expiry date of cookie changed :" +"username ="+cookie_value);
}
</script>
</head>
<body>
<form name="myForm">
Enter Username : <input type="text" id="username">
<input type="button" value="Extend Expiry Date" onclick="changedate()">
</form>
</body>
</html>

We can set up a cookie that never expires in JavaScript using the following approach:
document.cookie = "cookieName= true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
(for more examples)
https://www.javatpoint.com/javascript-cookies
https://www.tutorialspoint.com/How-to-set-cookies-expiry-date-in-JavaScript

Prof. Pathan F. S 6 Jamia Polytechnic (0366)


Computer Dept. Akkalkuwa
Client Side Scripting Language : JavaScript
4.2 Browser
JavaScript provides WebAPIs and Interfaces (object types) that we can use while
developing web application or website. These APIs and objects help us in controlling the lifecycle
of the webpage and performing various actions like getting browser information, managing screen
size, opening and closing new browser window, getting URL information or updating URL,
getting cookies and local storage, etc.
The Interface (object types) which helps us interact with the browser window are known
as Browser objects. It‟s a group of objects which belongs to different WebAPIs but are used for
managing various browser related information and actions.
The browser objects are of various types, used for interacting with the browser and belong to
different APIs. The collection of these Browser objects is also known as Browser object Model
(BOM). The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
The objects listed below are called browser objects.
 Window - part of DOM API
 Navigator
 Document - part of DOM API
 Screen - property of Window object
 History - property of Window object
 Location - property of Window and Document object
Opening a window :
Open() function : is used to open new window from current window
Syntax : window.open(url, windowName, [windowFeatures]);
Example : WinOpen.html
function createWindow()
{
let url = "https://studytonight.com";
let win = window.open(url, "My New Window", "width=300, height=200");
document.getElementById("result").innerHTML = win.name + " - " + win.opener.location;
}
Giving the new window focus :
focus() function : specifies a method that sets the focus on current window.
blur() function : specifies a method that removes the focus from the current window.
Example : BlurFocus.html
function blurWin()
{
myWindow.blur();
}
function focusWin()
{
myWindow.focus();
}
Window position :
We can set the specified position of the new window by setting its top and left properties, it
specify the x and y coordinates of screen.
window.open(url, "My New Window", "left=100, top=100, width=300, height=200");
Prof. Pathan F. S 7 Jamia Polytechnic (0366)
Computer Dept. Akkalkuwa
Client Side Scripting Language : JavaScript
Changing the content of window :
We can change the content of various elements of window such as paragraph, division, table etc.
by providing „id‟ attribute.
function openWin() {
var myWindow = window.open("", "", "width=400, height=200");
myWindow.opener.document.getElementById("demo").innerHTML =
"A new window has been opened.";
}
Closing a window :
close() function : is used to close window. We can only close the window which is open with the
open() function.
function closeWin() {
myWindow.close();
}
Scrolling a web page :
We can scroll a webpage vertically and horizontally by using following function :
scrollTo() method scrolls the document to specified x , y coordinates in pixels
Syntax : window.scrollTo(x, y)
function scrollWin() {
window.scrollTo(300, 500);
}
scrollBy() method scrolls the document by the specified number of pixels.
Syntax : window.scrollBy(x, y)
function scrollWin(x, y) {
window.scrollBy(x, y);
}
For Example : scroll.html
Opening Multiple window at once :
We can open multiple window by using window.open() function multiple times. We can use for
loop to open multiple window.
Example : multiwindow.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Multiple Window</title>
<script>
function show()
{
var x = 200;
var y = 100;
for(var i=1;i<=5;i++)
{
mywin = window.open("","","width=100, height=100,top=" + x + ",left=" + y + ",status=1")
x = x+50;
y = y+50;
}
}
Prof. Pathan F. S 8 Jamia Polytechnic (0366)
Computer Dept. Akkalkuwa
Client Side Scripting Language : JavaScript
</script>
</head>
<body>
<input type="button" name="multiple" value="Show Multiple window" onclick="show()">
</body>
</html>

Creating a web page in new window :


We can create a webpage in new window with the help of write function of window object. We
can pass HTML code as string parameter in write function
function show()
{
var win = window.open("", "MyWindow", "width=100, height=100")
win.document.write("<h3>Hello World!!!</h3>")
}
JavaScript in URL’s:
JavaScript code can be included on the client side URL by using “javascript:” pseudo-protocol
specifier. It specifies that the body of URL is an arbitrary javascript code and is interpreted by
javascript interpreter.
The “javascript:” prefix in a URL tells the browser to execute the code as javascript.
Example :
javascript:alert("Hello World);
javascript:var now = new Date(); "The time is:" + now;
javascript: void window.open(http://www.google.com);
(For security reasons the recent browser are not allowing to execute the javascript code in URL)
JavaScript security:
Timers:
In JavaScript, a timer is created to execute a task or any function at a particular time. Basically,
the timer is used to delay the execution of the program or to execute the JavaScript code in a
regular time interval. With the help of timer, we can delay the execution of the code.
The setTimeout() method helps the users to delay the execution of code.
Syntax : window.setTimeout(function, milliseconds);

Prof. Pathan F. S 9 Jamia Polytechnic (0366)


Computer Dept. Akkalkuwa
Client Side Scripting Language : JavaScript
The setInterval() method repeats a given function at every given time-interval.
Syntax : window.setInterval(function, milliseconds);
The clearInterval() method stops the executions of the function specified in the setInterval()
method.
Example : for setTimeout() method
<h2>JavaScript Timing</h2>
<p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>
<button onclick="setTimeout(myFunction, 3000);">Try it</button>
<script>
function myFunction() {
alert('Hello');
}
</script>
Example : for setTimeout() and clearTimeout() method
<h2>JavaScript Timing</h2>
<p>Click "Try it". Wait 3 seconds. The page will alert "Hello".</p>
<p>Click "Stop" to prevent the first function to execute.</p>
<p>(You must click "Stop" before the 3 seconds are up.)</p>
<button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button>
<button onclick="clearTimeout(myVar)">Stop it</button>
<script>
function myFunction() {
alert("Hello");
}
Example : for setInterval() method
<h2>JavaScript Timing</h2>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<script>
setInterval(myTimer, 1000);
function myTimer() {
const d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
Output :
JavaScript Timing
A script on this page starts this clock:
7:52:29 PM
Browser location and history:
Browser Location : The Location object represents the current location (URL) of a document.
You can access the location object by referencing the location property of the window or
document object.
Properties of location objects are :
 window.location.href : returns the href (URL) of the current page
 window.location.hostname : returns the name of the internet host (of the current page)
 window.location.pathname returns the path and filename of the current page
Prof. Pathan F. S 10 Jamia Polytechnic (0366)
Computer Dept. Akkalkuwa
Client Side Scripting Language : JavaScript
 window.location.protocol returns the web protocol used (http: or https:)
 window.location.port() return to the port number of the internet host
 window.location.assign() loads a new document
Example : location.html
<!doctype html>
<head>
<title>Location object Properties</title>
<script>
function assign() {
window.location.assign("https://www.google.com")
}
</script>
</head>
<body>
<h3>Location Properties</h3>
<input type="button" value=" Assign" onclick="assign()"><br>
<script>
// Hostname
let x = location.hostname;
document.write("The host name is :"+ x +"<br>");
// href
x = location.href;
document.write("The URL name of page is :"+x +"<br>");
// protocol
x = location.protocol;
document.write("The Protocol is :"+x +"<br>");
// host
x = location.host;
document.write("The host is :"+x +"<br>");
// pathname
x = location.pathname;
document.write("The pathname is :"+x +"<br>");
// port
x = location.port;
document.write("The port no is :"+x +"<br>");
</script>
</body>
</html>

Prof. Pathan F. S 11 Jamia Polytechnic (0366)


Computer Dept. Akkalkuwa
Client Side Scripting Language : JavaScript
Browser History : Every web browser will store the data on which websites or webpages
opened during the session in a history stack. To access this history stack we need to use the
History object in JavaScript. History object to access the history stack in JavaScript. The URLs
of pages visited by the user are stored as a stack in the history object.
The forward() Method: This method is used to load the next URL in the history list. This is
the same as clicking the Forward button in the browser.
Syntax : window.history.forward()
The back() Method: This method is used to load the previous URL in the history list. This is
the same as clicking the backward button in the browser.
Syntax : window.history.back()
The go() Method: This method is used to loads a URL from the history list.
Syntax : window.history.go(integer)
The parameter specifies the URL from the history.
-1 : Loads the previous page, 0 : Reloads the page, 1 : Loads the next page
<!DOCTYPE html>
<html>
<head>
<script>
function NextPage() {
window.history.forward()
}
function previousPage() {
window.history.back();
}
function go() {
window.history.go(0);
}
</script>
</head>
<body>
<h1>Brower History</h1>
<form action="" name="form1">
back button : <input type="button"
value="Back" onclick="previousPage()"> <br>
forward button : <input type="button"
value="Forward" onclick="NextPage()"> <br>
Go button : <input type="button"
value="go" onclick="go()"> <br>
</form>
</body>
</html>
https://www.w3schools.com/js/js_ex_browser.asp
https://www.studytonight.com/javascript/javascript-window-object
https://www.javatpoint.com/javascript-timer
https://www.javascripttutorial.net/javascript-bom/javascript-location/

Prof. Pathan F. S 12 Jamia Polytechnic (0366)


Computer Dept. Akkalkuwa

You might also like