04.11.2015 Views

javascript

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

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

Chapter 19: Client - Side Storage<br />

},<br />

return cookieValue;<br />

set: function (name, value, expires, path, domain, secure) {<br />

var cookieText = encodeURIComponent(name) + “=” +<br />

encodeURIComponent(value);<br />

if (expires instanceof Date) {<br />

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

}<br />

if (path) {<br />

cookieText += “; path=” + path;<br />

}<br />

if (domain) {<br />

cookieText += “; domain=” + domain;<br />

}<br />

if (secure) {<br />

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

}<br />

},<br />

document.cookie = cookieText;<br />

unset: function (name, path, domain, secure){<br />

this.set(name, “”, new Date(0), path, domain, secure);<br />

}<br />

};<br />

The CookieUtil.get() method retrieves the value of a cookie with the given name. To do so, it looks<br />

for the occurrence of the cookie name followed by an equal sign in document.cookie . If that pattern is<br />

found, then indexOf() is used to find the next semicolon after that location (which indicates the end of<br />

the cookie). If the semicolon isn ’ t found, this means that the cookie is the last one in the string, so the<br />

entire rest of the string should be considered the cookie value. This value is decoded using<br />

decodeURIComponent() and returned. In the case where the cookie isn ’ t found, null is returned.<br />

The CookieUtil.set() method sets a cookie on the page and accepts several arguments: the name of<br />

the cookie, the value of the cookie, an optional Date object indicating when the cookie should be deleted,<br />

an optional URL path for the cookie, an optional domain for the cookie, and an optional Boolean value<br />

indicating if the secure flag should be added. The arguments are in the order in which they are most<br />

frequently used, and only the first two are required. Inside the method, the name and value are URL -<br />

encoded using encodeURIComponent(), and then the other options are checked. If the expires<br />

argument is a Date object, then an expires option is added using the Date object ’ s toGMTString()<br />

method to format the date correctly. The rest of the method simply builds up the cookie string and sets it<br />

to document.cookie .<br />

There is no direct way to remove existing cookies. Instead, you need to set the cookie again — with the<br />

same path, domain, and secure options — and set its expiration date to some time in the past. The<br />

CookieUtil.unset() method handles this case. It accepts four arguments: the name of the cookie to<br />

remove, an optional path argument, an optional domain argument, and an optional secure argument.<br />

621

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

Saved successfully!

Ooh no, something went wrong!