Professional Documents
Culture Documents
COM
Introduction to DOM
The Document Object Model is a programming API for documents. The object model
itself closely resembles the structure of the documents it models.
The Document Object Model (DOM) is a programming API for HTML and XML
documents. It defines the logical structure of documents and the way a document is
accessed and manipulated.
With the Document Object Model, programmers can create and build documents,
navigate their structure, and add, modify, or delete elements and content. Anything found
in an HTML or XML document can be accessed, changed, deleted, or added using the
Document Object Model, with a few exceptions
<TABLE>
<ROWS>
<TR>
<TD>Shady Grove</TD>
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
</TR>
</ROWS>
</TABLE>
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
The DOM is the present and future of browsers, and no doubt it will become the only supported
technique for both basic and advanced DHTML in the future.
The W3C DOM is supported by 5th generation browsers. These currently include:
Opera 7+
Internet Explorer 5+
ICEbrowser
WHY DOM?
An HTML page is rendered in a browser.The browser assembles all the elements in the
HTMLpage in memory and once done it renders these object in the browser window. Once the
page is rendered it can no longer recognize the individual elements.
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
Javascript enabled browsers are capable of recognizing individual elements using the
concept tof DOM.
The HTML objects which belong to DOM has a descending relationship with each other. The top
most object in DOM is Navigator. The next level is the DOCUMENT. The DOM continues to
encompass the individual elements of FORM.
Navigator
->Window
->Document
->Anchor
->Link
->Form
->textbox
->textarea
->radiobutton
->checkbox
->select
->button
JSSS use Javascript syntax to control a documents presentation styles. When a JSSS is
embedded in an HTML page, the Javascript DOM adds additional objects into the DOM.
JSSS DOM
Document
->Tags
-> P
->DIV
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
->SPAN
->H1 thru H6
->Classes
->Tag Names
->IDS
Since Javascript understands the Dom and can extend the DOM, Javascript understands objects.
Objectname.PropertyName=value
ObjectName.MethodName
Events: that allow Java code snippets to be mapped to appropriate event handlers.
Browser Objects
When any Javascript enabled browser loads a web page, the browser automatically
creates a number of Javascript Objects that map to the Dom. The java script code embedded
within <script> tag makes use of these objects to interact with the HTML objects in the page.
Navigator
A Javascript
enabled Window The web page
Browswer loaded
Document containing all
theHTML
Screen elements to
Location which javascript
requires access
EVENT History
Event
Common context area in Computer Memory
OBJECTS USE
NAVIGATOR To access information about the Browser
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
WINDOW To access a window/frame in a window
DOCUMENT To access the document currently loaded in
a window.
LOCATION To represent a URL
HISTORY To maintain the history of URL accessed.
Event To access info about the occurrence of
event.
EVENT Provides constants that are used to identify
Events.
SCREEN To access info’ about the size and color
depth of the screen.
I. Window Object
If a document contain frames (<frame> or <iframe> tags), the browser creates one window object
for the HTML document, and one additional window object for each frame.
Property Description
closed Returns a Boolean value indicating whether a window has been closed or not
defaultStatus Sets or returns the default text in the statusbar of a window
document Returns the Document object for the window
frames Returns an array of all the frames (including iframes) in the current window
history Returns the History object for the window
innerHeight Sets or returns the the inner height of a window's content area
innerWidth Sets or returns the the inner width of a window's content area
length Returns the number of frames (including iframes) in a window
location Returns the Location object for the window
name Sets or returns the name of a window
navigator Returns the Navigator object for the window
opener Returns a reference to the window that created the window
outerHeight Sets or returns the outer height of a window, including toolbars/scrollbars
outerWidth Sets or returns the outer width of a window, including toolbars/scrollbars
pageXOffset Returns the pixels the current document has been scrolled (horizontally) from
the upper left corner of the window
pageYOffset Returns the pixels the current document has been scrolled (vertically) from
the upper left corner of the window
parent Returns the parent window of the current window
screen Returns the Screen object for the window
screenLeft Returns the x coordinate of the window relative to the screen
screenTop Returns the y coordinate of the window relative to the screen
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
screenX Returns the x coordinate of the window relative to the screen
screenY Returns the y coordinate of the window relative to the screen
self Returns the current window
status Sets the text in the statusbar of a window
top Returns the topmost browser window
Method Description
alert() Displays an alert box with a message and an OK button
blur() Removes focus from the current window
clearInterval() Clears a timer set with setInterval()
clearTimeout() Clears a timer set with setTimeout()
close() Closes the current window
confirm() Displays a dialog box with a message and an OK and a Cancel button
createPopup() Creates a pop-up window
focus() Sets focus to the current window
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
open() Opens a new browser window
print() Prints the content of the current window
prompt() Displays a dialog box that prompts the visitor for input
resizeBy() Resizes the window by the specified pixels
resizeTo() Resizes the window to the specified width and height
scroll()
scrollBy() Scrolls the content by the specified number of pixels
scrollTo() Scrolls the content to the specified coordinates
setInterval() Calls a function or evaluates an expression at specified intervals (in
milliseconds)
setTimeout() Calls a function or evaluates an expression after a specified number of
milliseconds
A new browser window opens using the open() method of a window object.
window.open(URL,name,specs,replace)
In the above, all the fields (URL, name, specs, replace) given in arguments are optional.
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
The URL given in the argument of the open() method of window object specifies the URL of the
page to open. If the user does not mention any URL, then an empty window will be created and
opened.
The name field specified in the open() method of window object is a string denoting the name of
the new window. This can be used as the target attribute.
_blank This is a default value that denotes that the URL is loaded into a new window.
_parent This denotes that the URL is loaded into the parent frame.
_self This denotes and makes the URL replace the current page.
_top This denotes that the URL replaces any framesets that may be loaded.
name This denotes the name of the window.
setTimeout():
The setInterval() method of Window object is used to call a function or evaluate an expression at
specified intervals. The setTimeout() method of a window object performs in a similar manner. In
contrast to the setInterval() method, the setTimeout() method of window object is used to call a
function or evaluate an expression after a specified number of milliseconds. The setTimeout()
method helps schedule the expression or function for the time specified by the user. The function
given in arguments is called or the expression is evaluated after a specified number of
milliseconds given as argument in the setTimeout() method of window object.
window.setTimeout(expression/function, milliseconds)
setTimeout() example:
<html>
<head>
<script type="text/javascript">
function exf()
{
exforsys.close()
}
</script>
</head>
<body>
exforsys = window.open('','','width=100,height=200')
exforsys.document.write("Example on setTimeout()
method!")
exforsys.setTimeout('exf()', 7000)
</body></html>
The window exforsys is closed after seven seconds. The setTimeout() method is applied to the
window exforsys with a parameter passed as function exf(). This performs the action of closing
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
the window exforsys by the statement exforsys.close(). This is performed after 7 seconds
because the second parameter passed to the setTimeout() method is 7000 milliseconds.
clearTimeout():
If a user wishes to cancel the timeout set in the setTimeout() method, he or she can use the
clearTimeout() method of window object. The clearTimeout() method of a window object is used
to cancel a timeout set with the setTimeout() method.
window.clearTimeout(timeoutID)
The timeoutID given as argument in the clearTimeout() method is the ID that is declared or set
during the setTimeout() method.
<html>
<head>
<script type="text/javascript">
exforsys = setTimeout
("window.location='http://exforsys.com/test.html'",
5000); </script></head></html>
The above example sends the user to a new page test.html in exforsys.com after 5 seconds. The
setTimeout method calls the page after 5000 milliseconds or 5 seconds. The ID of the setTimeout
method is set to exforsys.
Using the clearTimeout() method of window object and the previous example to cancel the
timeout set in the setTimeout() method:
<html>
<head>
<script type="text/javascript">
clearTimeout (exforsys);
</script></head></html>
assign():
The assign method of location object is used for loading a new document.
location.assign(URL)
for example
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
<html>
<head>
<script type="text/javascript">
function test()
{
window.location.assign("http://www.exforsys.com")
}
</script>
</head>
<body>
<input type="button" value="Click Here For Loading New Document" onclick="test()" />
</body>
</html>
reload():
This method of location object is used for reloading the current document. The currently displayed
page in the window that owns the location object is reloaded. This means that the document that
owns the Location object is to be reloaded.
location.reload()
for example
<html>
<head>
<script type="text/javascript">
function test()
{
window.location.reload()
}
</script>
</head>
<body>
<input type="button" value="Click Here For ReLoading page" onclick="test()" />
</body>
</html>
replace():
As the name implies, the replace() method of location object replaces the current document with
a new one. The current History entry is replaced with the URL specified in the replace method.
NOTE: The programmer must know that after the replace method is called he or she cannot go
back to the previous URL by using the back button.
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
location.replace(URL)
for example
<html>
<head>
<script type="text/javascript">
function exareplace()
{
window.location.replace("http://www.exforsys.com")
}
</script>
</head>
<body>
<input type="button" value="Click Here to Replace" onclick="exareplace()" />
</body>
</html>
III.SCREEN OBJECT
Property Description
availHeight Returns the height of the screen (excluding the Windows Taskbar)
availWidth Returns the width of the screen (excluding the Windows Taskbar)
colorDepth Returns the bit depth of the color palette for displaying images
height Returns the total height of the screen
pixelDepth Returns the color resolution (in bits per pixel) of the screen
width Returns the total width of the screen
Property Description
appCodeName Returns the code name of the browser
appName Returns the name of the browser
appVersion Returns the version information of the browser
cookieEnabled Determines whether cookies are enabled in the browser
platform Returns for which platform the browser is compiled
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
userAgent Returns the user-agent header sent by the browser to the server
Method Description
javaEnabled() Specifies whether or not the browser has Java enabled
taintEnabled() Specifies whether or not the browser has data tainting enabled
V.History Object
The history object contains the URLs visited by the user (within a browser window).
The history object is part of the window object and is accessed through the window.history
property.
Property Description
length Returns the number of URLs in the history list
Method Description
back() Loads the previous URL in the history list
forward() Loads the next URL in the history list
go() Loads a specific URL from the history list
<html>
<head>
<script type="text/javascript">
function funback()
{
window.history.back()
}
</script>
</head>
<body><form>
<input type="button" value="Press the Button to go
to Previous Page!!!" onclick="funback()" /> </form>
</body></html>
VI.Document Object
Each HTML document loaded into a browser window becomes a Document object.
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
The Document object provides access to all HTML elements in a page, from within a script.
Images
ImageMaps
Hyperlinks
Frames
Anchors
Applets
Mutimedia Objects
Form with various elements
The browser creates one array per HTML object thus registering each HTML Objects.
Image/Images array
Link/Links Array
Area
Frame/Frames Array
Anchor/Anchors array
Applet/Applets Array
Embed/Embeds Array
MimeType/MimeTypes array
Plugin/plugins array
Form/Forms array
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
document
title Sets or returns the title of the document Yes
URL Returns the full URL of the document Yes
Event HANDLING
Events are actions that can be detected by JavaScript, and the event object gives information
about the event that has occurred.
Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a
button.
Events are normally used in combination with functions, and the function will not be executed
before the event occurs!
1. Interactive event handlers- depends on user interactin with the HTML page ex.
Clicking a button
2. Non-Interactive event handlers-does not need user interaction. Ex. onload
Event Attributes
Below is the event attributes that can be inserted into different HTML elements to define event
actions.
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
onerror An error occurs when loading a document or an 4 1 9 Yes
image
onfocus An element gets focus 3 1 9 Yes
onkeydown A keyboard key is pressed 3 1 No Yes
onkeypress A keyboard key is pressed or held down 3 1 9 Yes
onkeyup A keyboard key is released 3 1 9 Yes
onload A page or image is finished loading 3 1 9 Yes
onmousedown A mouse button is pressed 4 1 9 Yes
onmousemove The mouse is moved 3 1 9 Yes
onmouseout The mouse is moved off an element 4 1 9 Yes
onmouseover The mouse is moved over an element 3 1 9 Yes
onmouseup A mouse button is released 4 1 9 Yes
onresize A window or frame is resized 4 1 9 Yes
onselect Text is selected 3 1 9 Yes
onunload The user exits the page 3 1 9 Yes
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
not an event is a bubbling event
cancelable Returns a Boolean value that indicates whether or No 1 9 Yes
not an event can have its default action prevented
currentTarget Returns the element whose event listeners triggered No 1 9 Yes
the event
eventPhase Returns which phase of the event flow is currently Yes
being evaluated
target Returns the element that triggered the event No 1 9 Yes
timeStamp Returns the time stamp, in milliseconds, from the No 1 9 Yes
epoch (system start or event trigger)
type Returns the name of the event
Form Object
Forms are used to collect user input, and contain input elements like text fields, checkboxes,
radio-buttons, submit buttons and more. A form can also contain select menus, textarea, fieldset,
legend, and label elements.
Text, textarea, radio, checkbox, button, submit, reset, select, option, password,
hidden, fileupload
The HTML Form elements that can be specified in the <input>tag are
<input type=”password”>
Button A button other than a submit/reset button
<input type=”button”>
Checkbox A check box <input type=”checkbox”>
Radio A radio button<input type=”radio”>
Reset A Reset Button <input type=”reset”>
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
Submit A submit button<input type=”submit”>
Select A selection list < select> <option>option1</option>
<option>option2</option>
</select>
Textarea A multiline textentry field <textarea> Default text </textarea>
Hidden A field that may contain a value but is not displayed within a
form <input type=”hidden”>
******Give sample prgms given in class for each of the FORM elements….. ************
Onblur() - fires when the form cursor is moved away from the object.
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
target Sets or returns the value of the target attribute in a form Yes
Date Object
Property Description
constructor Returns the function that created the Date object's prototype
prototype Allows you to add properties and methods to an object
Method Description
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
getTime() Returns the number of milliseconds since midnight Jan 1, 1970
getTimezoneOffset() Returns the time difference between GMT and local time, in minutes
getUTCDate() Returns the day of the month, according to universal time (from 1-31)
getUTCDay() Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear() Returns the year, according to universal time (four digits)
getUTCHours() Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds() Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes() Returns the minutes, according to universal time (from 0-59)
getUTCMonth() Returns the month, according to universal time (from 0-11)
getUTCSeconds() Returns the seconds, according to universal time (from 0-59)
getYear() Deprecated. Use the getFullYear() method instead
parse() Parses a date string and returns the number of milliseconds since
midnight of January 1, 1970
setDate() Sets the day of the month (from 1-31)
setFullYear() Sets the year (four digits)
setHours() Sets the hour (from 0-23)
setMilliseconds() Sets the milliseconds (from 0-999)
setMinutes() Set the minutes (from 0-59)
setMonth() Sets the month (from 0-11)
setSeconds() Sets the seconds (from 0-59)
setTime() Sets a date and time by adding or subtracting a specified number of
milliseconds to/from midnight January 1, 1970
setUTCDate() Sets the day of the month, according to universal time (from 1-31)
setUTCFullYear() Sets the year, according to universal time (four digits)
setUTCHours() Sets the hour, according to universal time (from 0-23)
setUTCMilliseconds() Sets the milliseconds, according to universal time (from 0-999)
setUTCMinutes() Set the minutes, according to universal time (from 0-59)
setUTCMonth() Sets the month, according to universal time (from 0-11)
setUTCSeconds() Set the seconds, according to universal time (from 0-59)
setYear() Deprecated. Use the setFullYear() method instead
toDateString() Converts the date portion of a Date object into a readable string
toGMTString() Deprecated. Use the toUTCString() method instead
toLocaleDateString() Returns the date portion of a Date object as a string, using locale
conventions
toLocaleTimeString() Returns the time portion of a Date object as a string, using locale
conventions
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
toLocaleString() Converts a Date object to a string, using locale conventions
toString() Converts a Date object to a string
toTimeString() Converts the time portion of a Date object to a string
toUTCString() Converts a Date object to a string, according to universal time
UTC() Returns the number of milliseconds in a date string since midnight of
January 1, 1970, according to universal time
valueOf() Returns the primitive value of a Date object
Math Object
Math is not a constructor. All properties/methods of Math can be called by using Math as an
object, without creating it.
Syntax
Property Description
E Returns Euler's number (approx. 2.718)
LN2 Returns the natural logarithm of 2 (approx. 0.693)
LN10 Returns the natural logarithm of 10 (approx. 2.302)
LOG2E Returns the base-2 logarithm of E (approx. 1.442)
LOG10E Returns the base-10 logarithm of E (approx. 0.434)
PI Returns PI (approx. 3.14159)
SQRT1_2 Returns the square root of 1/2 (approx. 0.707)
SQRT2 Returns the square root of 2 (approx. 1.414)
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2
radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
String Object
Syntax
or more simply:
Property Description
constructor Returns the function that created the String object's prototype
length Returns the length of a string
prototype Allows you to add properties and methods to an object
Method Description
charAt() Returns the character at the specified index
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a copy of the joined strings
fromCharCode() Converts Unicode values to characters
indexOf() Returns the position of the first found occurrence of a specified value in a
string
lastIndexOf() Returns the position of the last found occurrence of a specified value in a
string
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
match() Searches for a match between a regular expression and a string, and returns
the matches
replace() Searches for a match between a substring (or regular expression) and a
string, and replaces the matched substring with a new substring
search() Searches for a match between a regular expression and a string, and returns
the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
substr() Extracts the characters from a string, beginning at a specified start position,
and through the specified number of character
substring() Extracts the characters from a string, between two specified indices
toLowerCase() Converts a string to lowercase letters
toUpperCase() Converts a string to uppercase letters
valueOf() Returns the primitive value of a String object
Number Object
Syntax
Note: If the value parameter cannot be converted into a number, it returns NaN (Not-a-Number).
Property Description
constructor Returns the function that created the Number object's prototype
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
POSITIVE_INFINITY Represents infinity (returned on overflow)
prototype Allows you to add properties and methods to an object
Method Description
toExponential(x) Converts a number into an exponential notation
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
toFixed(x) Formats a number with x numbers of digits after the decimal point
toPrecision(x) Formats a number to x length
toString() Converts a Number object to a string
valueOf() Returns the primitive value of a Number object
COOKIES
A cookie, also known as a web cookie, browser cookie, and HTTP cookie, is a piece
of text stored on a user's computer by their web browser. A cookie can be used for
authentication, storing site preferences, shopping cart contents, the identifier for a server-based
session, or anything else that can be accomplished through storing text data.
Cookies are small amounts of data stored by the web browser. They allow you to store particular
information about a user and retrieve it every time they visit your pages. Each user has their own
unique set of cookies.
Cookies are typically used by web servers to perform functions such as tracking your visits to
websites, enabling you to log in to sites, and storing your shopping cart.
A cookie consists of one or more name-value pairs containing bits of information, which
may be encrypted for information privacy and data security purposes. The cookie is sent as a
field in the header of the HTTP response by a web server to a web browser and then sent back
unchanged by the browser each time it accesses that server.
Cookies may be set by the server with or without an expiration date. Cookies without an
expiration date exist until the browser terminates, while cookies with an expiration date may be
stored by the browser until the expiration date passes. Users may also manually delete cookies in
order to save space or to avoid privacy issues.
As text, cookies are not executable. Because they are not executed, they cannot
replicate themselves and are not viruses. However, due to the browser mechanism to set and
read cookies, they can be used as spyware. Anti-spyware products may warn users about some
cookies because cookies can be used to track computer activity—a privacy concern, later
causing possible malware.
TYPES OF COOKIES
Session cookie
A session cookie only lasts for the duration of users using the website. A session cookie will
expire if a user closes his/her browser, or if a user hasn't visited the server for certain period of
time (called session idle timeout), and the server would expire/invalidate the user session.
Persistent cookie
A persistent cookie will outlast user sessions. If a persistent cookie has Max-Age set to 1 year,
then, within the year, the initial value set in that cookie would be sent back to server every time
the user is visiting the server. This could be used to record a vital piece of information such as
how the user initially came to this website. For this reason, persistent cookie is also called
tracking cookie.
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
Secure cookie
A secure cookie is only used when a browser is visiting a server via HTTPS, that will make sure
that cookie is always encrypted when transmitting from client to server, and therefore less likely to
be exposed to cookie theft via eavesdropping.
HttpOnly cookie
HttpOnly cookie is still in IETF draft, though most of the modern browsers support it. On a
supported browser, a HttpOnly cookie will only be used when transmitting HTTP (or HTTPS)
requests, but the cookie value is not available to client side script, hence mitigate the threat of
cookie theft via Cross-site scripting.
Third-party cookie
First-party cookies are cookies set with the same domain or its subdomain in your browser's
address bar. Third-party cookies are cookies being set with different domains than the one shown
on address bar.
Super cookie
A Super cookie is a cookie with a Public Suffix domain, like .com, .co.uk or k12.ca.us.
Zombie cookie
A zombie cookie is any cookie that is automatically recreated after a user has deleted it. This is
accomplished by a script storing the content of the cookie in some other location, such as the
local storage available to Flash content, and then recreating it from the backup when the cookie's
absence is detected.
Setting a cookie
Transfer of Web pages follows the HyperText Transfer Protocol (HTTP). Regardless of cookies,
browsers request a page from web servers by sending them a usually short text called HTTP
request. For example, to access the page http://www.example.org/index.html, browsers connect
to the server www.example.org sending it a request that looks like the following one:
The server replies by sending the requested page preceded by a similar packet of text, called
'HTTP response'. This packet may contain lines requesting the browser to store cookies:
HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: name=value
Set-Cookie: name2=value2; Expires=Wed, 09 Jun 2021 10:18:14 GMT
(content of page)
browser ←------- server
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
The server sends lines of Set-Cookie only if the server wishes the browser to store cookies. Set-
Cookie is a directive for the browser to store the cookie and send it back in future requests to the
server (subject to expiration time or other cookie attributes), if the browser supports cookies and
cookies are enabled.
Cookies are like viruses in that they can infect the user's hard disks
Cookies generate pop-ups
Cookies are used for spamming
Cookies are used only for advertising
Cookies in JavaScript are accessed using the cookie property of the document object. In simple
Setting a cookie
To set a cookie, we set the document.cookie property to a string containing the properties of the
name=value This sets both the cookie's name and its value. username=matt
This optional value sets the date that the cookie will
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
blank, meaning that only the path that set the cookie
meaning that only the domain that set the cookie can
retrieve it.
secure This optional flag indicates that the browser should secure
Example
document.cookie = "username=John;
expires=15/02/2003 00:00:00";
This code sets a cookie called username, with a value of "John", that expires on Feb 15th, 2003
This code does exactly the same thing as the previous example, but specifies the date using the
Date.toGMTString() method instead. Note that months in the Date object start from zero, so
February is 01.
Another useful cookie-handling function is provided below. This function will "delete" the supplied
cookie from the browser by setting the cookie's expiry date to one second in the past.
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
{
cookie_date.setTime ( cookie_date.getTime() - 1 );
To use this function, just pass in the name of the cookie you would like to delete - for example:
delete_cookie ( "username" );
Retrieving cookies
To retrieve all previously set cookies for the current document, you again use the
WWW.VIDYARTHIPLUS.COM BATHUSHA