Title: Javascript III
1Javascript III
2Cookies
- A cookie is a small amount of data which is given
a name and stored by the browser. - A cookie is associated with a web page or web
site. - A cookie can be used to save state.
- Examples of cookie use
- Saving user preferences.
- Recalling user preferences.
- Saving and recalling state information.
- Enables information to be accessed by multiple
web pages. - Cookies can be written/read by CGI scripts and
JavaScript.
3Cookies in JavaScript
- cookie is a property of the document object.
- It is a string property allowing cookie(s) to be
- created
- read
- written
- deleted
- It has four additional attributes
- expires
- path
- domain
- secure
4Storing a simple cookie
- Set the cookie property to a string of the form
- name value
- For example
- document.cookie "email" escape(myEmail)
- Cookie values cannot contain semicolons, commas
or whitespace. - If you have such characters use
- escape()
- unescape()
5The lifetime of a cookie
- By default a cookie lasts only for the duration
of the browser session. - The expires attribute gets round this
- namevalue expiresdate
- For example to set a 1 yr expiry date
- var nextyear new Date()
- nextyear.setFullYear(nextyear.getFullYear() 1)
- document.cookie "email" escape(myEmail)
- " expires"
nextyear.toGMTString()
6The visibility of a cookie
- By default a cookie is visible to
- the web page which created it.
- other web pages in the same directory.
- other web pages in subdirectories.
- For example
- A cookie created by
- http//www.xx.com/eag/home/index.htm
- will be visible by
- http//www.xx.com/eag/home/another.htm
- http//www.xx.com/eag/home/scripts/newpage.htm
- but not by
- http//www.xx.com/eag/index.htm
7The path attribute
- The path attribute enables wider access to
cookies - namevalue pathURLpath
- For example
- A cookie created by
- http//www.xx.com/eag/home/index.htm
- with path set to
- path"/eag"
- will be visible to
- http//www.xx.com/eag/index.htm
- If the path is set to "/", the cookie is visible
to any page on the same server.
8Cookie domain
- By default cookies are only accessible to pages
on the same server. - To share across multiple servers use the domain
attribute - namevalue domaindomain_name
- For example
- A cookie created by
- http//www.server1.xx.com/eag/home/index.htm
- with path and domain set to
- path"/" domain"xx.com"
- will be visible to all pages on
- http//www.server1.xx.com http//www.server2.xx.
com
9Cookie security
- You cannot set the domain of a cookie to a domain
other than the domain of your server. - By default cookies are insecure and are
tramsmitted via a normal HTTP connection. - A cookie can be marked as secure which means it
is only transmitted when browser and server are
connected via HTTPS or other secure protocol. - This is done using the boolean secure attribute
- namevalue secure
10Reading a cookie
- When the cookie property is used it returns a
string. - This string contains all the cookies which apply
to the current document. - The string is a list of namevalue pairs
separated by semicolons. - You can parse this string to obtain the cookie
values.
11Limitations of Cookies
- Cookies are intended for infrequent storage of
small amounts of data. - Browsers not required to store more than 300
cookies. - Web servers not required to store more than 20
cookies (across all sites/pages on server) - Try to store multiple state variables within a
single named cookie.
12Demonstrationcookies1.htm
function GetName(myForm) var
allCookies document.cookie var pos
allCookies.indexOf("name") if (pos ! -1)
var start pos 5 var
end allCookies.indexOf("", start) if
(end -1) end allCookies.length
var name allCookies.substring(start,
end) name unescape(name)
myForm.result.value name
//--gt lt/scriptgt lt/headgt
lthtmlgt ltheadgt lttitlegt Cookies Example
lt/titlegt lt/headgt ltscript language"JavaScript"gt lt!
-- Hide JavaScript from old browsers function
SaveName(myForm) document.cookie
"name" escape(myForm.name.value)
13Demonstrationcookies1.htm
ltbodygt lth1gtCookies Examplelt/h1gt ltformgt ltinput
type "text" name "name" value ""gt ltinput
type "button" value"Save Name" onClick
"SaveName(this.form)"gt ltbrgt ltinput type
"text" name "result" value ""gt ltinput type
"button" value"Get Name" onClick
"GetName(this.form)"gt lt/formgt lt/bodygt lt/htmlgt
14Demonstrationcookies2.htm
lthtmlgt ltheadgt lttitlegt Cookies Example
lt/titlegt lt/headgt ltscript language"JavaScript"gt lt!
-- Hide JavaScript from old browsers function
Register(myForm) document.cookie
"name" escape(myForm.name.value)
document.cookie "address1"
escape(myForm.address1.value)
document.cookie "address2"
escape(myForm.address2.value)
document.cookie "city" escape(myForm.city.val
ue) document.cookie "county"
escape(myForm.county.value) document.cookie
"postcode" escape(myForm.postcode.value)
document.cookie "telephone"
escape(myForm.telephone.value)
document.cookie "email" escape(myForm.email.v
alue) //--gt lt/scriptgt lt/headgt
15Demonstrationcookies2.htm
ltbodygt lth1gtCookies Examplelt/h1gt ltpgtPlease fill in
the form below and click register to store your
detailslt/pgt ltformgt lttablegt lttrgtlttdgtNamelt/tdgt
lttdgtltinput type "text" name "name"
value ""gtlt/tdgt lt/trgt lttrgtlttdgtAddress
1lt/tdgt lttdgtltinput type "text" name
"address1" value ""gtlt/tdgt lt/trgt ETC.. lt/table
gt ltinput type "button" value"Register"
onClick "Register(this.form)"gt lt/formgt lthrgtTo
confirm these details click lta href"cookiesread.h
tm"gtherelt/agt. lt/bodygt lt/htmlgt
16Windows in JavaScript
- The window object allows operations to be
performed on browser windows. - Methods exist to
- open windows.
- close windows.
- move windows.
- size/resize windows.
- lose and gain window focus.
17Opening Windows
- To open a basic, empty window use
- var w window.open()
- Four optional parameters can be used to control
the window features - URL to be loaded when the window opens.
- Window name (used in TARGET attribute of ltformgt
or ltagt tags). If the window exists then this is
used. - Window size feature list (string comprised of a
comma-separated list of properties values). - Boolean argument indicating whether the URL
should replace the current entry in the window's
history list (true) or create a new entry
(false).
18Demonstrationwindow.htm
lthtmlgtltheadgt lttitlegt Window Example
lt/titlegt lt/headgt ltscript language"JavaScript"gt lt!
-- Hide JavaScript from old browsers var
winNum 0 function OpenWindow(myForm)
var winName winName "Win" winNum
winNum alert ("Creating window "
winName) window.open("", winName,"width400,
height350,statusyes,resizeableno")
//--gt lt/scriptgtlt/headgt ltbodygtlth1gtWindow
Examplelt/h1gt ltpgtPress the button below to open a
new windowltpgt ltformgt ltinput type "button"
value"Open Window" onClick "OpenWindow(this.for
m)"gt lt/formgtlt/bodygtlt/htmlgt
19Demonstrationwindow.htm
20Closing windows
- To close a specific window object, created within
the JavaScript - w.close()
- To close the window in which the JavaScript is
currently running - window.close()
- To avoid confusion with the document object do
not use - close()
21Window focus
- To give the keyboard focus on a particular
window - w.focus()
- To remove keyboard focus from a window
- w.blur()
22Demonstrationwindowfocus.htm
23Demonstrationwindowfocus.htm
lthtmlgt ltheadgt lttitlegt Window Example
lt/titlegt lt/headgt ltscript language"JavaScript"gt lt!
-- Hide JavaScript from old browsers var win1
var win2 function WindowOpen(win)
if (win 1) win1 window.open("win1.ht
m", "Win1","width400,height350,statusyes,resize
ableno") else win2
window.open("win2.htm", "Win2","width400,height3
50,statusyes,resizeableno")
function WindowFocus(win) if (win
1) win1.focus() else
win2.focus() function
WindowClose(win) if (win 1)
win1.close() else win2.close()
//--gt lt/scriptgt lt/headgt
24Demonstrationwindowfocus.htm
ltbodygtlth1gtWindow Examplelt/h1gt ltpgtPress the button
below to open a new windowltpgt ltformgt ltpgtltinput
type "button" value"Window 1 Open" onClick
"WindowOpen(1)"gtlt/pgt ltpgtltinput type "button"
value"Window 2 Open" onClick
"WindowOpen(2)"gtlt/pgt lthrgt ltpgtltinput type
"button" value"Window 1 Focus" onClick
"WindowFocus(1)"gtlt/pgt ltpgtltinput type
"button" value"Window 2 Focus" onClick
"WindowFocus(2)"gtlt/pgt lthrgt ltpgtltinput type
"button" value"Window 1 Close" onClick
"WindowClose(1)"gtlt/pgt ltpgtltinput type
"button" value"Window 2 Close" onClick
"WindowClose(2)"gtlt/pgt lt/formgt lt/bodygtlt/htmlgt
25Demonstrationwindowfocus.htm
26Window moving/sizing
- To move a window to absolute or relative
co-ordinates (refers to top left of window) - w.moveTo(x, y)
- w.moveBy(x, y)
- To resize to an absolute or relative size
- w.resizeTo(width, height)
- w.resizeBy(width, height)
- To scroll by an absolute or relative amount
- scrollTo(horizontal, vertical)
- scrollBy(horizontal, vertical)
- Note that parameters here are in pixels
27The location object
- The location object is a representation of the
URL for the document currently displayed in the
window. - Different parts of the URL can be identified
using properties. For example - protocol
- host
- pathname
- search (any portion of the URL following ? which
can be used for embedding arguments in a URL) - A new URL can be assigned to the location object
- document.location"http//www.cet.sunderland.ac.uk
/webeng/"
28Browser Detect example
- The location object can be used in the detection
of a JavaScript enabled browser. - If JavaScript is enabled it can load a new page.
- If JavaScript is not enabled the code is ignored
and the current page displayed (usually with a
hyperlink to a non-JavaScript area of the site).
29browserdetect1.htm
- ltbodygt
- lth1gtBrowser Reload Examplelt/h1gt
- ltscript language"JavaScript"gt
- lt!-- hide JavaScript from old browsers
- document.location "jsbrowser.htm"
- //--gt
- lt/scriptgt
- ltpgtThis browser does not support Javascript.lt/pgt
- lt/bodygt
30Demonstrationbrowserdetect1.htm
31A problem...
- Setting a new URL to the location object adds a
new entry in the browser history. - If "Back" is pressed we return to the page which
then runs the JavaScript and loads the current
page. - This effectively disables the "Back" button.
32browserdetect2.htm
- ltbodygt
- lth1gtBrowser Reload Examplelt/h1gt
- ltscript language"JavaScript"gt
- lt!-- hide JavaScript from old browsers
- location.replace("jsbrowser.htm")
- //--gt
- lt/scriptgt
- ltpgtThis browser does not support Javascript.lt/pgt
- lt/bodygt
33Demonstration browserdetect2.htm reload.htm
34JavaScript and Frames
- Each window has a frames property - frames .
- This refers to an array of window objects, each
referring to a frame within the window. - If a window has no frames the frames array is
empty and frames.length 0. - Each frame in a window can be referred to as
- frames0, frames1, etc
- If any of these frames have sub-frames then they
are further referred to as properties. For
example - frames1.frames2 (third sub-frame of second
frame!)
35Frame references
- Frames can be identified through the frames
hierarchy working down from - top (absolute top level frame)
- parent (relative to current frame)
- self (current frame)
- They can also be identified by name (often easier
than position in the frames array). - For example
- top.displayFrame.middleFrame
- parent.image_frame
36The frames hierarchy
frames0
self window
frames1
frames1.frames0
frames1.frames1
frames1.frames2
top parent self window parent.frames0 parent.fra
mes2 top.frames0 top.frames1
37Frames Example
- jsframes.htm defines two frames
- lthtmlgtltheadgtlttitlegtUsing Frames with
JavaScriptlt/titlegtlt/headgt - ltframeset rows"25,"gt
- ltframe src"jsframes_controls.htm"
name"control_frame"gt - ltframe src"jsframes_target.htm"
name"target_frame"gt - lt/framesetgt
- lt/htmlgt
38Frames example
- jsframes_controls.htm uses JavaScript to write to
target_frame. - ltbodygt
- lth1gtUpdating Frames Examplelt/h1gt
- ltpgtClick
- lta href"" onClick"top.target_frame.document.wri
teln('Hello World!ltbrgt')"gtherelt/agt - to update framelt/pgt
- lt/bodygt
- lt/htmlgt
39Demonstrationjsframes.htm
40Resources
- JavaScript
- David Flanagan, JavaScript The Definitive Guide,
3rd Edition, O'Reilly, 1998, ISBN 1-56592-392-8 - WebMonkey JavaScript Tutorial
- http//hotwired.lycos.com/webmonkey/programming/j
avascript/ - Material for this lecture came from these
resources