04.11.2015 Views

javascript

Create successful ePaper yourself

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

Chapter 19: Client - Side Storage<br />

string of all cookies available to the page (based on the domain, path, expiration, and security settings of<br />

the cookies) as a series of name - value pairs separated by semicolons, as in the following example:<br />

name1=value1;name2=value2;name3=value3<br />

All of the names and values are URL - encoded and so must be decoded via decodeURIComponent() .<br />

When used to set a value, the document.cookie property can be set to a new cookie string. That cookie<br />

string is interpreted and added to the existing set of cookies. Setting document.cookie does not<br />

overwrite any cookies unless the name of the cookie being set is already in use. The format to set a<br />

cookie is as follows, which is the same format used by the Set - Cookie header:<br />

name=value; expires=expiration_time; path=domain_path; domain=domain_name; secure<br />

Of these parameters, only the cookie ’ s name and value are required. Here’s a simple example:<br />

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

This code creates a session cookie called “ name ” that has a value of “ Nicholas ” . This cookie will be sent<br />

every time the client makes a request to the server; it will be deleted when the browser is closed. Although<br />

this will work, there are no characters that need to be encoded in either the name or value, so it ’ s best to<br />

always use encodeURIComponent() as shown in the following example when setting a cookie:<br />

document.cookie = encodeURIComponent(“name”) + “=” +<br />

encodeURIComponent(“Nicholas”);<br />

To specify additional information about the created cookie, just append it to the string in the same<br />

format as the Set - Cookie header, like this:<br />

document.cookie = encodeURIComponent(“name”) + “=” +<br />

encodeURIComponent(“Nicholas”) + “; domain=.wrox.com; path=/”;<br />

Since the reading and writing of cookies in JavaScript isn ’ t very straightforward, functions are often used<br />

to simplify cookie functionality. There are three basic cookie operations: reading, writing, and deleting.<br />

These are all represented in the CookieUtil object as follows:<br />

var CookieUtil = {<br />

get: function (name){<br />

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

cookieStart = document.cookie.indexOf(cookieName),<br />

cookieValue = null;<br />

if (cookieStart > -1){<br />

var cookieEnd = document.cookie.indexOf(“;”, cookieStart)<br />

if (cookieEnd == -1){<br />

cookieEnd = document.cookie.length;<br />

}<br />

cookieValue = decodeURIComponent(document.cookie.substring(cookieStart<br />

+ cookieName.length, cookieEnd));<br />

}<br />

620

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

Saved successfully!

Ooh no, something went wrong!