11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

When you assign a new cookie value to document.cookie, the current cookies are not<br />

replaced. <strong>The</strong> new cookie is parsed and its name/value pair is appended to the list. <strong>The</strong><br />

exception is when you assign a new cookie with the same name (and same domain and path, if<br />

they exist) as a cookie that already exists. In this case, the old value is replaced with the new.<br />

For example:<br />

document.cookie = "username=fritz";<br />

document.cookie = "username=thomas";<br />

alert("Cookies: " + document.cookie);<br />

<strong>The</strong> result is<br />

Reading Cookies<br />

As you can see from the previous example, reading cookies is as simple as examining the<br />

document.cookie string. Because the browser automatically parses and adds any cookies set<br />

into this property, it always contains up-to-date name/value pairs of cookies for the current<br />

document. <strong>The</strong> only challenging part is parsing the string to extract the information in which you<br />

are interested. Consider the following code:<br />

document.cookie = "username=fritz";<br />

document.cookie = "favoritecolor=green";<br />

document.cookie = "jsprogrammer=<br />

<strong>The</strong> value of document.cookie after these statements are executed is<br />

"username=fritz; favoritecolor=green; jsprogrammer=<br />

If you are interested in the favoritecolor cookie, you could manually extract everything after<br />

favoritecolor= and before ; jsprogrammer=. However, it is almost always a good idea to write<br />

a function that will do this for you automatically.<br />

Parsing Cookies<br />

<strong>The</strong> following code parses the current cookies and places them in an associative array indexed<br />

by name. It assumes that the browser is ECMAScript-compliant (nearly all modern browsers<br />

are).<br />

// associative array indexed as cookies["name"] = "value"<br />

var cookies = new Object();<br />

function extractCookies()

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!