Tải bản đầy đủ - 0 (trang)
Chapter 19. Cookies and Client-Side Persistence

Chapter 19. Cookies and Client-Side Persistence

Tải bản đầy đủ - 0trang

19.1.AnOverviewofCookies

Acookieisasmallamountofnameddatastoredbytheweb

browserandassociatedwithaparticularwebpageorwebsite.

[*]

Cookiesservetogivethewebbrowseramemorysothat

scriptsandserver-sideprogramscanusedatathatwasinputon

onepageonanotherpage,orsothebrowsercanrecalluser

preferencesorotherstatevariableswhentheuserleavesa

pageandthenreturns.Cookieswereoriginallydesignedfor

server-sideprogramming,andatthelowestlevel,theyare

implementedasanextensiontotheHTTPprotocol.Cookiedata

isautomaticallytransmittedbetweenthewebbrowserandweb

server,soserver-sidescriptscanreadandwritecookievalues

thatarestoredontheclient.Asyou'llsee,JavaScriptcanalso

manipulatecookiesusingthecookiepropertyoftheDocument

object.

[*]Thename"cookie"doesnothavealotofsignificance,butitisnotusedwithoutprecedent.Intheobscure

annalsofcomputinghistory,theterm"cookie"or"magiccookie"hasbeenusedtorefertoasmallchunkof

data,particularlyachunkofprivilegedorsecretdata,akintoapassword,thatprovesidentityorpermitsaccess.

InJavaScript,cookiesareusedtosavestateandcanestablishakindofidentityforawebbrowser.Cookiesin

JavaScriptdonotuseanykindofcryptography,however,andarenotsecureinanyway(althoughtransmitting

themacrossanencryptedhttps:connectionhelps).



cookieisastringpropertythatallowsyoutoread,create,



modify,anddeletethecookieorcookiesthatapplytothe

currentwebpage.Althoughcookieappearsatfirsttobea

normalread/writestringproperty,itsbehaviorisactuallymore

complex.Whenyoureadthevalueofcookie,yougetastring

thatcontainsthenamesandvaluesofallthecookiesthatapply

tothedocument.Youcreate,modify,ordeleteanindividual

cookiebysettingthevalueofthecookiepropertyusingaspecial

syntax.Latersectionsofthischapterexplainindetailhowthis

works.Tousethecookiepropertyeffectively,however,youneed

toknowmoreaboutcookiesandhowtheywork.

Inadditiontoanameandavalue,eachcookiehasoptional



attributesthatcontrolitslifetime,visibility,andsecurity.

Cookiesaretransientbydefault;thevaluestheystorelastfor

thedurationoftheweb-browsersessionbutarelostwhenthe

userexitsthebrowser.Ifyouwantacookietolastbeyonda

singlebrowsingsession,youmusttellthebrowserhowlong

youwouldlikeittoretainthecookie.Theoriginalwaytodothis

wasbysettingtheexpiresattributetoanexpirationdateinthe

future.Whiletheexpiresattributestillworks,ithasbeen

supersededbythemax-ageattribute,whichspecifiesthelifetime,

inseconds,ofthecookie.Settingeitheroftheseattributes

causesthebrowsertosavethecookieinalocalfilesothatit

canreaditbackinduringfuturebrowsingsessionsiftheuser

revisitsthewebpage.Oncetheexpirationdatehaspassed,or

themax-agelifetimehasbeenexceeded,thebrowser

automaticallydeletesthecookiefromitscookiefile.

Anotherimportantcookieattributeispath,whichspecifiesthe

webpageswithwhichacookieisassociated.Bydefault,a

cookieisassociatedwith,andaccessibleto,thewebpagethat

createditandanyotherwebpagesinthesamedirectoryorany

subdirectoriesofthatdirectory.Ifthewebpage

http://www.example.com/catalog/index.htmlcreatesacookie,

forexample,thatcookieisalsovisibleto

http://www.example.com/catalog/order.htmland

http://www.example.com/catalog/widgets/index.html,butitis

notvisibletohttp://www.example.com/about.html.

Thisdefaultvisibilitybehaviorisoftenexactlywhatyouwant.

Sometimes,though,you'llwanttousecookievaluesthroughout

awebsite,regardlessofwhichpagecreatesthecookie.For

instance,iftheuserentershismailingaddressinaformonone

page,youmaywanttosavethataddresstouseasthedefault

thenexttimehereturnstothepageandalsoasthedefaultin

anentirelyunrelatedformonanotherpagewhereheisasked

toenterabillingaddress.Toallowthisusage,youspecifyapath

forthecookie.Then,anywebpagefromthesamewebserver

thatcontainsthatpathinitsURLcansharethecookie.For



example,ifacookiesetby

http://www.example.com/catalog/widgets/index.htmlhasits

pathsetto"/catalog",thatcookieisalsovisibleto

http://www.example.com/catalog/order.html.Or,ifthepathis

setto"/",thecookieisvisibletoanypageonthe

www.example.comwebserver.

Bydefault,cookiesareaccessibleonlytopagesonthesame

webserverfromwhichtheywereset.Largewebsitesmay

wantcookiestobesharedacrossmultiplewebservers,

however.Forexample,theserveratorder.example.commay

needtoreadcookievaluessetfromcatalog.example.com.This

iswherethenextcookieattribute,domain,comesin.Ifacookie

createdbyapageoncatalog.example.comsetsitspathattribute

to"/"anditsdomainattributeto".example.com",thatcookieis

availabletoallwebpagesoncatalog.example.com,

orders.example.com,andanyotherserverintheexample.com

domain.Ifthedomainattributeisnotsetforacookie,thedefault

isthehostnameofthewebserverthatservesthepage.Note

thatyoucannotsetthedomainofacookietoadomainother

thanthedomainofyourserver.

Thefinalcookieattributeisabooleanattributenamedsecure

thatspecifieshowcookievaluesaretransmittedoverthe

network.Bydefault,cookiesareinsecure,whichmeansthat

theyaretransmittedoveranormal,insecureHTTPconnection.

Ifacookieismarkedsecure,however,itistransmittedonly

whenthebrowserandserverareconnectedviaHTTPSor

anothersecureprotocol.

Notethattheexpires,max-age,path,domain,andsecureattributesof

acookiearenotJavaScriptobjectproperties.Laterinthe

chapter,you'llseehowtosetthesecookieattributes.

Cookieshavegottenabadreputationformanywebusers

becauseoftheunscrupuloususeofthird-partycookiescookies

associatedwiththeimagesonawebpageratherthantheweb

pageitself.Third-partycookiesenableanad-hostingcompany



totrackauserfromoneclientsitetoanotherclientsite,for

example,andtheprivacyimplicationsofthispracticecause

someuserstodisablecookiesintheirwebbrowsers.Before

usingcookiesinyourJavaScriptcode,youmaywanttofirst

checkthattheyareenabled.Inmostbrowsers,youcandothis

bycheckingthenavigator.cookieEnabledproperty.Iftrue,cookies

areenabled,andiffalse,cookiesaredisabled(although

nonpersistentcookiesthatlastforonlythecurrentbrowsing

sessionmaystillbeenabled).Thisisnotastandardproperty,

andifyoufindthatitisundefinedinthebrowseryourcodeis

runningin,youmusttestforcookiesupportbytryingtowrite,

read,anddeleteatestcookie.I'llexplainhowtodothese

thingslaterinthechapter,andExample19-2includescodefor

testingforcookiesupport.

Ifyouareinterestedinthecompletetechnicaldetailsofhow

cookieswork(attheHTTPprotocollevel),seeRFC2965at

http://www.ietf.org/rfc/rfc2965.txt.Cookieswereoriginally

createdbyNetscape,andNetscape'soriginalcookie

specificationisstillofinterest.Althoughpartsofitarenow

obsolete,itismuchshorterandeasiertoreadthantheformal

RFC.Findthisolddocumentat

http://wp.netscape.com/newsref/std/cookie_spec.html.

Thesectionsthatfollowdiscusshowyoucansetandquery

cookievaluesinJavaScriptandhowyoucanspecifytheexpires,

path,domain,andsecureattributesofacookie.Thesearefollowed

byasectiononcookiealternatives.



19.2.StoringCookies

Toassociateatransientcookievaluewiththecurrent

document,simplysetthecookiepropertytoastringoftheform:

name=value



Forexample:



document.cookie="version="+encodeURIComponent(document.last



Thenexttimeyoureadthecookieproperty,thename/valuepair

youstoredisincludedinthelistofcookiesforthedocument.

Cookievaluesmaynotincludesemicolons,commas,or

whitespace.Forthisreason,youmaywanttousethecore

JavaScriptglobalfunctionencodeURIComponent()toencodethe

valuebeforestoringitinthecookie.Ifyoudothis,you'llhave

tousethecorrespondingdecodeURIComponent()functionwhenyou

readthecookievalue.(Itisalsocommontoseecodethatuses

theolderescape()andunescape()functions,butthesearenow

deprecated.)

Acookiewrittenwithasimplename/valuepairlastsforthe

currentweb-browsingsessionbutislostwhentheuserexits

thebrowser.Tocreateacookiethatcanlastacrossbrowser

sessions,specifyitslifetime(inseconds)withamax-age

attribute.Youcandothisbysettingthecookiepropertytoa

stringoftheform:

name=value;max-age=seconds



Forexample,tocreateacookiethatpersistsforayear,youcan

usecodelikethis:

document.cookie="version="+document.lastModified+

";max-age="+(60*60*24*365);



Youcanalsospecifythelifetimeofacookiewiththeobsolete

expiresattribute,whichshouldbesettoadateintheformat

writtenbyDate.toGMTString().Forexample:

varnextyear=newDate();

nextyear.setFullYear(nextyear.getFullYear()+1);

document.cookie="version="+document.lastModified+

";expires="+nextyear.toGMTString();



Similarly,youcansetthepath,domain,andsecureattributesofa

cookiebyappendingstringsofthefollowingformattothe

cookievaluebeforethatvalueiswrittentothecookieproperty:

;path=path

;domain=domain

;secure



Tochangethevalueofacookie,setitsvalueagainusingthe

samename,path,anddomainalongwiththenewvalue.You

canchangethelifetimeofacookiewhenyouchangeitsvalue

byspecifyinganewmax-ageorexpiresattribute.

Todeleteacookie,setitagainusingthesamename,path,and

domain,specifyinganarbitrary(orempty)value,andamax-age

attributeof0(orusetheexpiresattributetospecifyan

expirationdatethathasalreadypassed).Notethatthebrowser



isnotrequiredtodeleteexpiredcookiesimmediately,soa

cookiemayremaininthebrowser'scookiefilepastits

expirationdate.



19.2.1.CookieLimitations

Cookiesareintendedforinfrequentstorageofsmallamountsof

data.Theyarenotintendedasageneral-purpose

communicationordata-transfermechanism,soyoushoulduse

theminmoderation.RFC2965encouragesbrowser

manufacturerstoallowunlimitednumbersofcookiesof

unrestrictedsize.Youshouldknow,however,thatthestandard

doesnotrequirebrowserstoretainmorethan300cookies

total,20cookiesperwebserver(fortheentireserver,notjust

foryourpageorsiteontheserver),or4KBofdatapercookie

(bothnameandvaluecounttowardthis4KBlimit).Inpractice,

modernbrowsersallowmanymorethan300cookiestotal,but

the4KBsizelimitisstillenforcedbysome.



19.3.ReadingCookies

WhenyouusethecookiepropertyinaJavaScriptexpression,

thevalueitreturnsisastringthatcontainsallthecookiesthat

applytothecurrentdocument.Thestringisalistofname=value

pairsseparatedbysemicolons,wherenameisthenameofa

cookie,andvalueisitsstringvalue.Thisvaluedoesnotinclude

anyoftheattributesthatmayhavebeensetforthecookie.To

determinethevalueofaparticularnamedcookie,youcanuse

theString.indexOf()andString.substring()methods,oryoucan

useString.split()tobreakthestringintoindividualcookies.

Onceyouhaveextractedthevalueofacookiefromthecookie

property,youmustinterpretthatvaluebasedonwhatever

formatorencodingwasusedbythecookie'screator.For

example,thecookiemightstoremultiplepiecesofinformation

incolon-separatedfields.Inthiscase,youwouldhavetouse

appropriatestringmethodstoextractthevariousfieldsof

information.Don'tforgettousethedecodeURIComponent()function

onthecookievalueifitwasencodedusingthe

encodeURIComponent()function.

Thefollowingcodeshowshowtoreadthecookieproperty,

extractasinglecookiefromit,andusethevalueofthatcookie:



//Readthecookieproperty.Thisreturnsallcookiesforthis

varallcookies=document.cookie;

//Lookforthestartofthecookienamed"version"

varpos=allcookies.indexOf("version=");



//Ifwefindacookiebythatname,extractanduseitsvalue

if(pos!=-1){

varstart=pos+8;//Startofcook

varend=allcookies.indexOf(";",start);//Endofcookie

if(end==-1)end=allcookies.length;

varvalue=allcookies.substring(start,end);//Extractt



value=decodeURIComponent(value);//Decodeit



//Nowthatwehavethecookie

value,wecanuseit.

//Inthiscase,thecookiewaspreviouslysettothemodif

//dateofthedocument,sowecanuseittoseeifthedoc

//changedsincetheuserlastvisited.

if(value!=document.lastModified)

alert("Thisdocumenthaschangedsinceyouwerelasthe

}



Notethatthestringreturnedwhenyoureadthevalueofthe

cookiepropertydoesnotcontainanyinformationaboutthe

variouscookieattributes.Thecookiepropertyallowsyoutoset

thoseattributes,butitdoesnotallowyoutoreadthem.



19.4.CookieExample

Weendthisdiscussionofcookieswithausefulutilityfor

workingwithcookies,shownalittlelaterinExample19-2.The

Cookie()constructorreadsthevalueofanamedcookie.The

store()methodofacookiestoresdatainthatcookie,usingthe

lifetime,path,anddomainyouspecify,andtheremove()method

ofacookiedeletesthecookiebysettingitsmax-ageattributeto

0.

TheCookieclassdefinedinthisexamplestoresthenamesand

valuesofmultiplestatevariablesinasinglecookie.Toassociate

datawithacookie,simplysetpropertiesoftheCookieobject.

Whenyoucallthestore()methodonthecookie,thenamesand

valuesofthepropertiesyouhaveaddedtotheobjectbecome

thecookievaluethatissaved.Similarly,whenyoucreateanew

Cookieobject,theCookie()constructorlooksforanexisting

cookiewiththenameyouhavespecified.Ifitfindsit,itparses

itsvalueasasetofname/valuepairsandsetsthemas

propertiesofthenewlycreatedCookieobject.

TohelpyouunderstandExample19-2,Example19-1begins

withasimplewebpagethatusestheCookieclass.



Example19-1.UsingtheCookieclass









TheCookieclassitselfislistedinExample19-2.



Example19-2.ACookieutilityclass



/**

*ThisistheCookie()constructorfunction.

*

*Thisconstructorlooksforacookiewiththespecifiednameforthe

*currentdocument.Ifoneexists,itparsesitsvalueintoasetof

*name/valuepairsandstoresthosevaluesaspropertiesofthenewlycreated

*object.

*

*Tostorenewdatainthecookie,simplysetpropertiesoftheCookie

*object.Avoidpropertiesnamed"store"and"remove",sincetheseare

*reservedasmethodnames.

*

*Tosavecookiedatainthewebbrowser'slocalstore,callstore().

*Toremovecookiedatafromthebrowser'sstore,callremove().

*

*ThestaticmethodCookie.enabled()returnstrueifcookiesare

*enabledandreturnsfalseotherwise.

*/

functionCookie(name){

this.$name=name;//Rememberthenameofthiscookie

//First,getalistofallcookiesthatpertaintothisdocument.

//WedothisbyreadingthemagicDocument.cookieproperty.

//Iftherearenocookies,wedon'thaveanythingtodo.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 19. Cookies and Client-Side Persistence

Tải bản đầy đủ ngay(0 tr)

×