HTML5 and CSS3, Second Edition

(singke) #1

sessionStorage


We can use localStorage for things that we want to persist even after our users close
their web browsers, but sometimes we need a way to store some information while
the browser is open and throw it away once the session is over. That’s where session-
Storage comes into play. It works the same way as localStorage, but the contents of the
sessionStorage are cleared out once the browser session ends. Instead of grabbing the
localStorage object, you grab the sessionStorage object.

sessionStorage.setItem('name','BrianHogan');
varname= sessionStorage.getItem('name');

This is a lot more convenient than a cookie-based approach.

Falling Back


The localStorage method works on all modern browsers and a few older ones,
so we don’t need a client-side fallback solution. However, there’s no way to
share the data we store in localStorage with the server or another computer, so
if users make settings changes at home, those changes won’t be available on
the users’ work computers. Additionally, it’s not going to work if users disable
JavaScript. So, a good fallback solution would be to persist these settings to
a server. For an application like this, we could save the settings to the server
when the user presses the Submit button, linking the settings with a user
record. We’d craft the form so that it submits directly to the server, and we’d
alter the page so that if there are no client-side settings, the server-side set-
tings would be used. Unfortunately, writing a server-side solution is beyond
the scope of this book.

Web Storage is a simple approach for storing small bits of data, but it has
performance limitations on mobile devices and isn’t a good fit for lots of data.
Let’s look at how we can store more complex data structures client-side.

report erratum • discuss

Saving Preferences with Web Storage • 189


Download from Wow! eBook <www.wowebook.com>

Free download pdf