Cookies A cookie is a small text file written to the client's computer • Purpose • Write information that lives after the browser exits • Keep track of form data submitted multiple times during a particular visit • Track user purchase and visit habits • Examples • Log-in account and password so the information doesn't broadcast over the web • Shopping cart information • Personalized greeting when the user next visits a site
What's in a cookie • The cookie name and cookie value • A cookie's expiration data • Path to the page creating the cookie • Domain name of the server creating the cookie • Security parameter that can restrict access to it Create a cookiedocument.cookie = "userName=John doe"; Cookie name is 'userName' Cookie value is 'John doe' The first '=' is an assignment to the cookie property in the document object Read a cookie Alert(document.cookie); Notes: The browser normally sets items 3, 4, and 5 Syntax: [name]=[values];expires=[date];secure; path=[path];domain=[domain]
Expiration Dates • Browsers hold cookies in memory • When a browser exits, it writes all cookies to disk • Browsers don’t save cookies that don’t have expiration dates • How to set a cookie with an expiration date Var theName = document.someForm.name.value; document.cookie = "user="+theName + ";expires=" + expDate.toGMTString(); • We'll describe expDate on the next slide Question: What use are cookies without an expiration date?
Computing an expiration date • Instructions to set an expiration date var expDate = new Date(); var thirtyDaysMillis = 30*24*60*60*1000; var future = expDate.getTime() + thirtyDaysMillis; expDate.setTime(future); • A short cut with fewer variables var expDate = new Date() expDate.setTime(expDate.getTime() + 30*24*60*60*1000); expDate.setTime(future); • Another way to do it var expDate = new Date(); expDate.setMonth(expDate.getMonth() + 1);
Writing Multiple Cookies • Just store over the cookie property more than once • Each store creates a new cookie • Example • document.cookie = "name=Bill"; • document.cookie = "address=1250 Siskiyou blvd"; • document.cookie = "city=Ashland"; • document.cookie = "state=OR"; • document.cookie = "zip=97520"; Note: This creates five cookies.
Splitting Cookies in Pieces Question: What's in theCookies? • The split function does it! • Assume the cookies are:Name=bill;address=1250 Siskiyou blvd;city=Ashland;state=OR;zip=97520 • Here is the code var cookies = document.cookie; var theCookies = cookies.split(";"); alert(theCookies.split("=")); alert(theCookies.split("=")); alert(theCookies.split("=")); alert(theCookies.split("=")); alert(theCookies.split("=")); Bill 1250 Siskiyou blvd Ashland OR 97520 theCookies = name=bill theCookies = address=1250 Siskiyou blvd theCookies = city=Ashland