Using the Web Storage API
The W3C Web Storage API is a specification for persistent data storage of key-value pair data in Web clients. It was originally part of the HTML5 spec and you’ll still hear it called HTML5 storage a lot online, but it was separated out into its own spec for boring reasons (read: politics). Lump me in with the people still calling it HTML5 storage.
Basically we’re talking a key value store, ala localStorage.setItem(“myvar”, “myvalue”), stored by the browser. Browser support for web storage is solid: Chrome, Safari, Firefox, Opera, and IE (v8) support web storage. You wouldn’t want make-or-break stuff on your app using HTML5 storage for those folks still puttering along with old IE releases, but for extra or optional features it works great.
On one of my sites I decided to use HTML5 storage to store the most recently selected address, so when a user comes back to the site it’ll start right back where they left off. What could have been an exercise in cookie setting and maintenance took about 5 minutes.
First, I went to the function that’s setting the selected address (item.row.objectid is the unique address key) and dropped this in:
The first line confirms the browser supports HTML5 storage. If it’s supported, I set a local storage item called gp_lastSelected with my key value. Now whenever an address is selected, that key value is set.
To finish, I went to my onLoad event and tossed this in:
I confirm HTML5 storage support, then I check to see if I have a gp_lastSelected value set, and if I do I process my function to select that address, which zooms to the location and makes it the active record for the data reports. That easy.
- They get sent back and fourth between the browser and server every time a request is make, slowing things down.
- You have to do the cookie expiry date dance.
- They don't hold a lot (~4k I think).
- Cookies are site specific, while localStorage is domain specific. With localStorage you can access a key-value from any site on the domain, so you can share data across sites.
- Unlike cookies, HTML5 storage can do session storage as well, using sessionStorage in the exact same manner as localStorage.
HTML5 storage is where things are headed, with every major browser supporting the new spec, and its ready to use now. As you can see, using it couldn’t be easier.