View
44
Download
1
Category
Preview:
DESCRIPTION
JavaScript 3 Windows and Cookies. Dr Kevin McManus http://staffweb.cms.gre.ac.uk/~mk05/web/JavaScript/JavaScript3.html. URL of document of document to load. name that can be used as a target for links. variable to store the reference to the window. - PowerPoint PPT Presentation
Citation preview
JavaScript 3
JavaScript 3
Windows and Cookies
Dr Kevin McManushttp://staffweb.cms.gre.ac.uk/~mk05/web/JavaScript/JavaScript3.html
© 27/04/2012 University of Greenwich 2
JavaScript 3
Windows
• Independent browser windows can be created using window.open()
mywin = window.open("advert1.html", "adwin",
"width=500, height=50, status=no, resizable=no");
URL of document of document to load
name that can be used as a target for links
variable to store the reference to
the window
window features - check the documentation for the
full range of features
© 27/04/2012 University of Greenwich 3
JavaScript 3
Windows• Various method can be used to control the window e.g.:
mywin.focus()
• will put the window on top and give it keyboard focus
mywin.moveTo(200, 100)
• will move the window to the specified x, y screen location
mywin.close()
• will close the window• no way to prevent the user closing the window for themselves
© 27/04/2012 University of Greenwich 5
JavaScript 3
indWin.html
var helpwin = null;
function showHelp() { helpwin = window.open("helptext.html","help", "toolbar=no,location=no,directories=no,status=no," + "menubar=no,scrollbars=yes,resizable=yes," + "width=400,height=200"); helpwin.focus()}
function closewin(){ if (helpwin != null && !helpwin.closed) helpwin.close();}
function to close the help window
global variable to hold a reference to the window
function to open the help window
© 27/04/2012 University of Greenwich 6
JavaScript 3
indWin.html
<body onunload="closewin()"><h1>Using an Independent Window</h1><p>Imagine that this is a complicated page that you may need help with.</p><p>Clicking the "help" button will open a separate window containing a document giving helpful advice.The window will be closed when you leave this page.</p><p><input type="button" value="Help" onclick="showHelp()"/></p></body> button to open
the help window
close the help window when we leave
© 27/04/2012 University of Greenwich 7
JavaScript 3
helptext.html
• The file displayed in the help window
<body><h1>Help</h1><p>Imagine, if you, can that this is a page full of really helpful information.</p><p><input type="button" value="Close Help" onclick="window.close()"/></p></body>
button to close the help window
© 27/04/2012 University of Greenwich 8
JavaScript 3
indWin.html
• Moving the window to the front using the focus() method
• Is it a good idea to make the window NOT resizable by the user?
• Why does helpwin need to be a global variable• declared outside functions as opposed to being a local variable
declared inside a function?
function showHelp() { helpwin = window.open("helptext.html","help", "toolbar=no,location=no,directories=no,status=no," + "menubar=no,scrollbars=yes,resizable=yes," + "width=400,height=200"); helpwin.focus()}
© 27/04/2012 University of Greenwich 9
JavaScript 3
indWin.html• Closing the windows when the user leaves the page
• windows created like this are truly independent and will persist even after the user has moved to another page or even closed the original browser window
• to be tidy the code should close the window when the user leaves the page.
<body onunload="closewin()">
function closewin(){ if (helpwin != null && !helpwin.closed) helpwin.close(); }
• How could helpwin be null?• How could helpwin have a status of closed?
© 27/04/2012 University of Greenwich 10
JavaScript 3
indWin.html
• Allowing the user to close the help window from helptext.html
<input type="button" value="close help"
onclick="window.close()">
• Is this really necessary?
• Are popup windows always a good thing?
© 27/04/2012 University of Greenwich 11
JavaScript 3
Quick Quiz
• Imagine the following JavaScript function is called by the onLoad event for a document
• What do you think its effect is?
function openwin() { if (mywin == null || mywin.closed) mywin = window.open("advert.html", "adwin", "width=500,height=50, status=no, resizable=no, dependent=yes"); setTimeout("openwin()", 3000); }
© 27/04/2012 University of Greenwich 12
JavaScript 3
Dynamically generated window content
• Each window object contains a document object that represents the current document on display
• Use the write() method of the document object associated with the window
errorwin.document.write("Your input contained errors");
• Here errorwin is a reference to a previously opened window
• Whenever you write to a document the content will be appended to the previous content
• If you wish to replace the previous content you must close the document (not the window!) first
errorwin.document.close();
JavaScript 3
mailingList2.htmlfunction Validate(theForm) { var missing = ""; if (theForm.Title.value == "") missing += "<li>Title</li>"; if (theForm.Initials.value == "") missing += "<li>Initials</li>"; if (theForm.Surname.value == "") missing += "<li>Surname</li>"; if (theForm.Email.value == "") missing += "<li>Email</li>";
var platSelected = false; for (i = 0; i < theForm.Platforms.length; i++) { if (theForm.Platforms[i].checked) platSelected = true; }
if (!platSelected) missing += "<li>Platform</li>";
if (missing != "") { openwin(); errorwin.document.write("You missed the following essential elements:<ul>" + missing + "</ul>Please complete and resubmit."); errorwin.focus(); errorwin.document.close(); return false; } else { closewin(); return true; }}
if anything is missing open the error window, write to it’s document, bring it into
focus and return false
HTML format error message
otherwise close the error window and
return true
© 27/04/2012 University of Greenwich 15
JavaScript 3
mailingList2.html• The principle is exactly the same as for the previous
version of this program (mailingList.html)• With this version the errors are displayed an independent
window rather than an alert box.
• From the user's point of view what might be the advantages and disadvantages of each method?
© 27/04/2012 University of Greenwich 16
JavaScript 3
Quick Quiz• In mailingList2.html what would happen if this line in Validate()
errorwin.document.close();• were replaced by this line errorwin.close();
• Would it be possible to have both a help window and an error window in the same application?
• Suppose you displayed an image in an independent window
mywin.document.write("<img src='happy.gif'/>");
• What line of code would need to be executed subsequently to change the image on display to sad.gif?
© 27/04/2012 University of Greenwich 17
JavaScript 3
Cookies
• Small items of data stored by a browser• on behalf of a server
server sends a cookie to the
browser in the HTTP response
browser sends the cookie back to the
server on all subsequent HTTP
requests
© 27/04/2012 University of Greenwich 18
JavaScript 3
Cookies
• Used to give the browser a memory, i.e. store "state"
• use data from one page in another (e.g. login authentication)
• save data between a user's visit to the site (e.g. progress through a tutorial, page preferences)
• Different browsers store cookies in different ways
• Mozilla browsers let you manage your cookies• Cookies can also be manipulated by client-side
JavaScript code
© 27/04/2012 University of Greenwich 19
JavaScript 3
Limitations of cookies• Size
• browser is only required to store 4k bytes per cookie• browser only has to store 20 per server
• after that it may overwrite old ones
• Format• just a string of data
• Unreliable• user may refuse to accept cookies• user may delete the cookie file
• Location • personal to the machine not the user• a cookie stored by IE won't be retrieved by Firefox
• Security• can be manipulated with JavaScript using document.cookie
© 27/04/2012 University of Greenwich 20
JavaScript 3
Advantages of Cookies
• Scalable• unlike server side session variables/objects• uses client memory/disk
• Persistent• unlike session variables/objects• may last only as long as the browser
• session cookie• may last indefinitely
• Convenient• especially for implementing session variables/objects
© 27/04/2012 University of Greenwich 21
JavaScript 3
Cookie attributes• Cookies have four optional attributes that control their lifetime,
visibility and security.
• expires• default is transient - they expire when the user exits the browser• If an expiry time is set the browser will store the cookie until the expiry
time• unless someone decides to delete it of course!
• domain• the cookie can be made available to domains other than the servers that
sent the cookie• the cookie can be made available to other servers in the same domain
as the server that sent the cookie • if an HTTP response from www.foobar.com sets a cookies with the domain
attribute set to foobar.com then it will be returned in all HTTP requests to servers in the domain foobar.com, e.g. fred.foobar.com
© 27/04/2012 University of Greenwich 22
JavaScript 3
Cookie attributes
• path • controls visibility to other documents on the same server• by default cookie is visible to:
• document that created it• other documents in the same directory• other documents in subdirectories of directory of the document that
created it
• by setting the path it can be made available to documents in other directories on the same server
• "/" means all directories
• secure• if secure is set the cookie will only be transmitted over the
internet via a secure protocol• HTTPS - HTTP over SSL
© 27/04/2012 University of Greenwich 23
JavaScript 3
Quick Quiz
If shoptroll.html sets a cookie which other files by default are allowed access to it?
© 27/04/2012 University of Greenwich 24
JavaScript 3
Javascript and Cookies• Setting a cookie
• Easy! Just give it a name and assign it's name, value and attributes to document.cookie e.g.
document.cookie = "uname=fred;expires=Fri, 5 Apr 2002 15:17:01"
• Reading a cookie• Tricky! When you read document.cookie you see
the whole list of cookies that you are allowed access• You have to search through to extract the one you
want - e.g. document.cookie may contain the string:
last=9827; uname=fred; pword=x59d; search=beans
© 27/04/2012 University of Greenwich 27
JavaScript 3
cookie.html
function storeName(theForm){ var theName = theForm.username.value; var expire = new Date(); expire.setMonth(expire.getMonth() + 6) var expireGMT = expire.toGMTString(); document.cookie = "uname=" + theName + "; expires=" + expireGMT;
alert("Hi " + theName + " I'll remember you next time you visit"); document.cookie = "secret=shhh";}
get the name from the form
calculate an expiry date 6 months from now
report back to the userset a secret cookie
convert the expiry date to the correct
string format
set the cookie
function to store the cookie
© 27/04/2012 University of Greenwich 28
JavaScript 3
cookie.html
function deleteName() { var expire = new Date(); expire.setDate(expire.getDate() - 1) var expireGMT=expire.toGMTString(); document.cookie = "uname=; expires=" + expireGMT;}
no need to give the cookie a value
convert the expiry date to the correct
string format
function to delete the cookie set an expiry date 1 day in the past
JavaScript 3
cookie.html<script type="text/javascript"><!--var allCookies = document.cookie;var start = allCookies.indexOf("uname=");if (start != -1) { start += 6; var end = allCookies.indexOf(";", start); if (end == -1) end = allCookies.length; var theName = allCookies.substring(start, end); document.write("<p>Welcome back " + theName + "!</p>"); document.write("<p>"); document.write("<input type='button' value='forget me‘ onclick='deleteName()'/>"); document.write("</p>");} else { document.write("<p>Hello - I don't think we've met</p>"); document.write("<p>Please tell me your name</p>"); document.write("<p><form action=\"dummy\">"); document.write("<input type='text' name='username'/>"); document.write("<input type='button' value='enter' onclick='storeName(this.form)'/>"); document.write("</form></p>");}// --></script><p><input type="button" value="show cookie setting" onclick="alert(document.cookie)"/></p></body>
if the uname cookie exists
otherwise prompt the user for their name
find the value of uname in the cookie
welcome the user back
create a button to delete the cookie
create a button to store the cookie
© 27/04/2012 University of Greenwich 30
JavaScript 3
cookie.html Questions
• How long will the cookie named "secret" last?• What do you think the format for setting the path
attribute is?• Why doesn't assigning the "secret" cookie to document.cookie overwrite and so destroy the "uname" cookie?
• How can the script tell if the cookie was stored successfully?
• What if the user has disabled cookies on their browser?
© 27/04/2012 University of Greenwich 31
JavaScript 3
Reading a Cookie• document.cookie contains a list of all cookies
that your document is allowed to see
<input type="button" value="show cookie setting" onclick="alert(document.cookie)"/>
• You have to write code to search through the document.cookie string and find the cookie that you want
© 27/04/2012 University of Greenwich 32
JavaScript 3
Reading a Cookie
• The string method indexOf(foo) returns the index of “foo” in the string or -1 if “foo” is not found
• The string method substring() returns the string between two indices
var mytext = "snakevinyl";var start = mytext.indexOf("kev");var end = start + 5;var name = mytext.substring(start,end);
calculate the index of the
last character
name gets the value ‘kevin’
start gets the value 3
© 27/04/2012 University of Greenwich 33
JavaScript 3
Reading a Cookie
• You don't know where in the document.cookie string your cookie is.
• Use indexOf() to search for the name of your cookie and store the index number of the first character• if indexOf() returns -1 if the cookie doesn’t exist
• Add the length of the cookie name (plus one for the "=" character) to the index number so that it points to the first character of the cookie value
• Use indexOf() again to search from that position onwards for the next ";" character and store that value
• Use the string method substring() to extract the string between the two index values
© 27/04/2012 University of Greenwich 34
JavaScript 3
Quick Quiz
• Suppose the cookie name for cookie.html was changed from "uname" to "username“• Which lines of code in cookie.html would have
to be changed?
© 27/04/2012 University of Greenwich 35
JavaScript 3
cookieTrolley.htmlA Cookie Based Shopping Trolley
• This example illustrates a number of important cookie concepts:• cookies as a way of maintaining "state" during an
extended dialogue with the user • using cookies to send data to a server-side script (the
"checkout" script in this case)• dealing with the limited number of cookies that the
browser will maintain• the need to "escape" reserved characters in cookie
values (semicolons, commas or whitespace)
© 27/04/2012 University of Greenwich 36
JavaScript 3
Maintaining State During a Dialogue
• A problem with web applications that engage in a dialogue with the
user which extends over several interactions is where and how to
store the "state" of the dialogue
• For example with a shopping trolley application the user may
repeatedly add or remove things from the shopping trolley before
finally proceeding to the checkout. Where and how should the
current contents of the shopping trolley be stored?
• There are several answers to this question
• server-side solutions are more commonly used
• client-side solutions can offer advantages
• cookieTrolley.html presents a JavaScript solution based on the use
of a cookie
JavaScript 3
cookieTrolley.html
response from the server-side script Checkout.php
response from the server-side script
ProcessOrder.php
© 27/04/2012 University of Greenwich 39
JavaScript 3
cookieTrolley.html
var trollwin = null;
function addToTrolley(prodList){ var selection = prodList.selectedIndex; if (selection != -1) { var selectedProd = prodList.options[selection].text; document.cookie = "trolley=" + escape(getTrollContents()) + "&" + escape(selectedProd); if (document.cookie.indexOf("trolley=") == -1) alert("This application won't work as you're not accepting cookies"); } displayTrolley();}
function to add items to the trolley
display the trolley contents in trollwin
test the cookie and report back to the user
add the current selection to the trolley cookie
global variable to hold the independent window
reference
© 27/04/2012 University of Greenwich 40
JavaScript 3
cookieTrolley.html
function getTrollContents () { var allCookies = document.cookie; var start = allCookies.indexOf("trolley="); if (start != -1) { start += 8; var end = allCookies.indexOf(";", start); if (end == -1) end = allCookies.length; var trollContents = allCookies.substring(start, end); return unescape(trollContents); } else { return ""; }}
and return the value
otherwise return an empty string
if it exists then extract its value
function to get the contents from the
trolley cookie look for a cookie called trolley
© 27/04/2012 University of Greenwich 41
JavaScript 3
cookieTrolley.htmlfunction displayTrolley(){ var contents = getTrollContents(); var contentsArray = contents.split("&"); openwin(); trollwin.document.write ("<p><b>Your trolley contains:</b></p>"); if (contentsArray.length < 2) { trollwin.document.write("<p>no items</p>"); } else { trollwin.document.write("<ul>"); for (var i = 1; i < contentsArray.length; i++) { trollwin.document.write ("<li>" + contentsArray[i] + "</li>"); } trollwin.document.write("</ul>"); } trollwin.document.close(); trollwin.focus();}
otherwise format the contents as an
unordered list
tell the user if the cookie is empty
bring the trolley window to the front
write into the independent window
function to display the cookie contents
© 27/04/2012 University of Greenwich 42
JavaScript 3
cookieTrolley.htmlfunction goToCheckout(theForm){ var contents = getTrollContents(); if (contents.length == 0) { alert("Nothing in trolley"); } else { theForm.submit(); } return false;}
function openwin() { if (trollwin == null || trollwin.closed){ trollwin = window.open("","win1", "toolbar=no,location=no,directories=no,status=no,menubar=no," + "scrollbars=yes,resizable=yes,width=300,height=200"; }}
function closewin(){ if (trollwin != null && !trollwin.closed) trollwin.close();}
functions to open and close the independent trolley window
function to check that the trolley is not empty before submitting to the
server-side checkout
© 27/04/2012 University of Greenwich 43
JavaScript 3
cookieTrolley.html<body onunload="closewin()" onload="displayTrolley()"><h2>Shopping Trolley - client-side cookie example</h2><form action="Checkout.php"><p><select name="products" size="1"> <option>camera</option> <option>power drill</option> <option>food mixer</option> <option>vacuum cleaner</option> <option>cuddly toy</option></select><input type="button" value="add" onclick="addToTrolley(this.form.products)"/><input type="button" value="remove" onclick="removeFromTrolley(this.form.products)"/></p><p><input type="button" value="show trolley" onclick="displayTrolley()"/></p><hr /><p><input type="submit" value="go to the checkout" onclick="return goToCheckout(this.form)"/>On the server</p></form></body>
open and close the trolley window
form submits to a server-side script Checkout.php
© 27/04/2012 University of Greenwich 44
JavaScript 3
cookieTrolley.html• A lot of this code should be familiar from previous examples
• Manipulating a separate window • the functions closewin(), openwin() are as seen before• displayTrolley() writes to the window using
trollwin.document.write
• Storing and retrieving cookies• use of indexOf() and substring() to isolate the cookie value in the
function getTrollContents()• assigning the new value to document.cookie
• Getting hold of the value of an item selected from a drop-down list
function addToTrolley(prodList){ var selection = prodList.selectedIndex; if (selection != -1) { var selectedProd = prodList.options[selection].text;
© 27/04/2012 University of Greenwich 45
JavaScript 3
Storing Multiple Values in a Single Cookie
• Browsers are only required to store a maximum of 20 cookies from each server
• When this limit is exceeded the browser may begin to randomly delete cookies
• How do you deal with this if you have multiple values to store• perhaps the user adds lots of items to their shopping trolley?
• Answer - store multiple value in a single cookie• So rather than
cookie1=value1; cookie2=value2; cookie3=value3• Have
cookie1=value1 and value2 and value3
© 27/04/2012 University of Greenwich 46
JavaScript 3
Storing Multiple Values in a Single Cookie
• Q. how do you keep the values separate?• A. choose some character that will never appear in a
cookie value to be a delimiter • in this case the ampersand character (&) has been chosen
trolley=camera&cuddly toy&food mixer&power drill
• cookieTrolley.html has been coded so there will always be an initial “&”
trolley=&camera&cuddly toy&food mixer&power drill
• Some server-side technologies have built-in ways of dealing with multiple values• e.g. PHP can treat the cookie value as an array.
© 27/04/2012 University of Greenwich 47
JavaScript 3
Storing Multiple Values in a Single Cookie
• Insert the delimiter into the cookie as each new value is appended• imagine that document.cookie already contains:
trolley=&camera&power drill• and the new value "cuddly toy" is to be added
• So afterwards the cookie will be:
trolley=&camera&power drill&cuddly toy
function addToTrolley(prodList){ ...... document.cookie = "trolley=" + escape(getTrollContents()) + "&" + escape(selectedProd);
ignore the use of the escape() function for now
© 27/04/2012 University of Greenwich 48
JavaScript 3
Storing Multiple Values in a Single Cookie
• The delimiters have to be taken into account when accessing the cookie contents
• The string method split() will divide a string based on a given character and return an array of substrings
• Imagine the cookie value is trolley=&camera&power drill
function displayTrolley(){ var contents = getTrollContents(); var contentsArray = contents.split("&"); ...... for ( var i = 1; i < contentsArray.length; i++ ) { trollwin.document.write ("<li>" + contentsArray[i] + "</li>"); }
contentsArray[1] will be “camera” and
contentsArray[2] will be “power drill”
loop through the array to output the contents as an unordered list
© 27/04/2012 University of Greenwich 49
JavaScript 3
Storing Multiple Values in a Single Cookie• Cookie values are not allowed to contain semicolons, commas or
whitespace.• These value have special meaning
• in cookies themselves (“;” is used to divide cookies and their attributes)• as part of the HTTP header to and from the server.
• Data that may include any of these values must be encoded using the escape() function before it is stored in the cookie.
• It then needs to be "unescaped" to convert it back before being displayed.
function addToTrolley(prodList){ ...... document.cookie = "trolley=" + escape(getTrollContents()) + "&" + escape(selectedProd);
function getTrollContents () { ...... return unescape(trollContents);
© 27/04/2012 University of Greenwich 50
JavaScript 3
Using cookies to send data to a server-side script
• No special code is needed to do this • Cookies and their values are automatically sent as part of the HTTP
header with requests to the server and are thus accessible to server-side scripts.
• The mechanism for getting hold of the cookie value in the server-side script depends on the technology used
• PHP makes cookie handling painless e.g. the PHP code to access the cookie in Checkout.php is:
$items = explode('&', $_COOKIE['trolley']); $numItems = count($items); echo('<p>Trolley contains</p>'); echo('<ol>'); for ( $i=1; $i<$numItems; ++$i ){ echo("<li>$items[$i]</li>\n") } echo('</ol>');
gets the cookie called ‘trolley’ and splits the
values using an ampersand delimiter
© 27/04/2012 University of Greenwich 51
JavaScript 3
Quick Quiz• What will happen to the shopping trolley contents if the
user surfs off to another site and then returns to the shopping trolley page?
• What will happen to the shopping trolley contents when the user exits from the browser?
• When looping through the array containing the trolley contents in displayTrolley() why is var i initialised to 1 and not 0?
for ( var i = 1; i < contentsArray.length; i++ ) { trollwin.document.write ("<li>" + contentsArray[i] + "</li>");
© 27/04/2012 University of Greenwich 52
JavaScript 3
Cookie Functions// cookies functions (c) k.mcmanus@gre.ac.uk
function setCookie(cookieName,cookieValue) { var expire = new Date(); expire.setYear(expire.getYear() + 1901); var expireGMT = expire.toGMTString(); document.cookie = cookieName + "=" + cookieValue + "; expires=" + expireGMT;}
function getCookie(cookieName) { var allCookies = document.cookie; var begin = allCookies.indexOf(cookieName); if ( begin != -1 ) { begin = begin + cookieName.length + 1; var end = allCookies.indexOf(";", begin); if (end == -1) end = allCookies.length; return allCookies.substring(begin, end); } else return null;}
Use these functions to make your life easier when dealing with cookies
© 27/04/2012 University of Greenwich 53
JavaScript 3
Don't Forget
• When developing with JavaScript....
• use alerts as print statements
• use the Firefox Error Console• or some other tool
© 27/04/2012 University of Greenwich 54
JavaScript 3
Summary• We have seen how JavaScript can be used to
control independent browser windows• modal control of dependent windows has not been
covered• frames operate in much the same way but are not
available under XHTML1.1• Cookies are a small string of information
relating to a web server stored by the browser• can be manipulated by both server-side scripts and
client-side JavaScript• despite their limitations and vulnerabilities they are an
important and useful mechanism to record state in web applications
Recommended