1 / 55

JavaScript 3 Windows and Cookies

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.

Download Presentation

JavaScript 3 Windows and Cookies

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavaScript 3Windows and Cookies Dr Kevin McManus http://staffweb.cms.gre.ac.uk/~mk05/web/JavaScript/JavaScript3.html

  2. 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 Windows • Independent browser windows can be created usingwindow.open() mywin = window.open("advert1.html", "adwin", "width=500, height=50, status=no, resizable=no"); University of Greenwich

  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 University of Greenwich

  4. Independent Help Window University of Greenwich

  5. indWin.html global variable to hold a reference to the window 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 open the help window function to close the help window University of Greenwich

  6. indWin.html close the help window when we leave <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 University of Greenwich

  7. 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 University of Greenwich

  8. indWin.html 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() } • 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? University of Greenwich

  9. 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? University of Greenwich

  10. 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? University of Greenwich

  11. 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); } University of Greenwich

  12. 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(); University of Greenwich

  13. mailingList2.html University of Greenwich

  14. HTML format error message if anything is missing open the error window, write to it’s document, bring it into focus and return false otherwise close the error window and return true mailingList2.html function 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; } }

  15. 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? University of Greenwich

  16. 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? University of Greenwich

  17. browser sends the cookie back to the server on all subsequent HTTP requests server sends a cookie to the browser in the HTTP response Cookies • Small items of data stored by a browser • on behalf of a server University of Greenwich

  18. 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 University of Greenwich

  19. 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 University of Greenwich

  20. 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 University of Greenwich

  21. 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 University of Greenwich

  22. 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 University of Greenwich

  23. Quick Quiz If shoptroll.html sets a cookie which other files by default are allowed access to it? University of Greenwich

  24. 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 University of Greenwich

  25. cookie.html University of Greenwich

  26. cookie.html University of Greenwich

  27. get the name from the form function to store the cookie calculate an expiry date 6 months from now convert the expiry date to the correct string format set the cookie report back to the user set a secret cookie cookie.html function storeName(theForm){ var theName = theForm.username.value; var expire = newDate(); 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"; } University of Greenwich

  28. function to delete the cookie set an expiry date 1 day in the past convert the expiry date to the correct string format no need to give the cookie a value cookie.html function deleteName() { var expire = newDate(); expire.setDate(expire.getDate() - 1) var expireGMT=expire.toGMTString(); document.cookie = "uname=; expires=" + expireGMT; } University of Greenwich

  29. if the uname cookie exists find the value of uname in the cookie welcome the user back create a button to delete the cookie otherwise prompt the user for their name create a button to store the cookie 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>

  30. 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? University of Greenwich

  31. 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 University of Greenwich

  32. Reading a Cookie • The string methodindexOf(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 start gets the value 3 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’ University of Greenwich

  33. 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 University of Greenwich

  34. 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? University of Greenwich

  35. 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) University of Greenwich

  36. 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 University of Greenwich

  37. cookieTrolley.html

  38. cookieTrolley.html response from the server-side script Checkout.php response from the server-side script ProcessOrder.php

  39. global variable to hold the independent window reference function to add items to the trolley add the current selection to the trolley cookie test the cookie and report back to the user display the trolley contents in trollwin 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(); } University of Greenwich

  40. function to get the contents from the trolley cookie look for a cookie called trolley if it exists then extract its value and return the value otherwise return an empty string 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""; } } University of Greenwich

  41. function to display the cookie contents write into the independent window tell the userif the cookie is empty otherwise format the contents as an unordered list bring the trolley window to the front cookieTrolley.html function 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(); } University of Greenwich

  42. function to check that the trolley is not empty before submitting to the server-side checkout functions to open and close the independent trolley window cookieTrolley.html function 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(); } University of Greenwich

  43. cookieTrolley.html open and close the trolley window <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> form submits to a server-side script Checkout.php University of Greenwich

  44. 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; University of Greenwich

  45. 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 University of Greenwich

  46. 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. University of Greenwich

  47. 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 University of Greenwich

  48. 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 contentsArray[1] will be “camera” and contentsArray[2] will be “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>"); } loop through the array to output the contents as an unordered list University of Greenwich

  49. 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); University of Greenwich

  50. 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 University of Greenwich

More Related