18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Cookies in <strong>JavaScript</strong><br />

Dealing with cookies in <strong>JavaScript</strong> is a little complicated because of a notoriously poor interface. The<br />

document object has a property called cookie, which is a single string containing all cookies accessible<br />

by the given page. The cookie property is also unique in that setting it to a specific value only alters the<br />

cookies available to the page; it doesn’t actually change the value of cookie itself. This functionality is<br />

part of the BOM and, as such, isn’t guided by any sort of specifications (which explains its lack of logic).<br />

To create a cookie, you must create a string in the following format:<br />

cookie_name=cookie_value; expires=expiration_time; path=domain_path;<br />

domain=domain_name; secure<br />

Only the first part of the string, specifying the name and value, is mandatory to set a cookie; all other<br />

parts are optional. This string is then set to the document.cookie property to create the cookie. <strong>For</strong><br />

example, to set a simple cookie, use the following:<br />

document.cookie = “name=Nicholas”;<br />

document.cookie = “book=” + encodeURIComponent(“<strong>Professional</strong> <strong>JavaScript</strong>”);<br />

Reading the value of document.cookie gives access to these cookies, along with all others accessible<br />

from the given page. If you display the value of document.cookie after running the two lines of the<br />

previous code, it equals “name=Nicholas; book=<strong>Professional</strong>%20<strong>JavaScript</strong>”. Even if other<br />

cookie attributes are specified, such as an expiration time, document.cookie only returns the name<br />

and value of each cookie with a semicolon separating the cookies.<br />

Because creating and reading cookies requires remembering this format, most developers use functions<br />

to handle the details. The function to create a cookie is the easiest:<br />

function setCookie(sName, sValue, oExpires, sPath, sDomain, bSecure) {<br />

var sCookie = sName + “=” + encodeURIComponent(sValue);<br />

if (oExpires) {<br />

sCookie += “; expires=” + oExpires.toGMTString();<br />

}<br />

if (sPath) {<br />

sCookie += “; path=” + sPath;<br />

}<br />

if (sDomain) {<br />

sCookie += “; domain=” + sDomain;<br />

}<br />

if (bSecure) {<br />

sCookie += “; secure”;<br />

}<br />

Client-Server Communication<br />

}<br />

document.cookie = sCookie;<br />

483

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

Saved successfully!

Ooh no, something went wrong!