HTML5 and CSS3, Second Edition

(singke) #1

CHAPTER 9


Saving Data on the Client


Remember when cookies were awesome? Neither do I. Cookies have been
rather painful to deal with since they came on the scene, but we put up with
the hassle because they’ve been the only reliable way to store information on
the clients’ machines.

To use cookies, we have to name them and set their expiration. This involves
a bunch of JavaScript code we wrap in a function so we never have to think
about how it actually works, kind of like this:

html5_localstorage/setcookie.js
// via http://www.javascripter.net/faq/settinga.htm
functionSetCookie(cookieName,cookieValue,nDays){
vartoday=newDate();
varexpire=newDate();
if(nDays==null|| nDays==0)nDays=1;
expire.setTime(today.getTime()+ 3600000*24*nDays);

document.cookie= cookieName+"="+escape(cookieValue)
+";expires="+expire.toGMTString();
}

Aside from the hard-to-remember syntax, there are also the security concerns.
Some sites use cookies to track users’ surfing behavior, so users disable
cookies in some fashion or delete them frequently.

HTML5 introduces new options for storing data on the client: Web Storage
(using either localStorage or sessionStorage),^1 IndexedDB,^2 and Web SQL
Databases.^3 These new methods are incredibly powerful and reasonably
secure. Best of all, they’re implemented today by several browsers, including


  1. http://www.w3.org/TR/webstorage/

  2. http://www.w3.org/TR/IndexedDB

  3. http://www.w3.org/TR/webdatabase/


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf