HTML5, Part III: Local Storage

In the beginning, there were cookies. The cookies were tasty, and removed the need to log in to websites every time, although some people didn’t like them due to privacy concerns. But cookies were sent with every HTTP request, usually unencrypted, slowing down the session and possibly exposing sensitive information. Plus they could only hold 4 kb of data, which is fine for remembering someone’s username but not much more.

Then HTML5 appeared, and it had in its specification a new thing, Web Storage. Web storage was like cookies, but it was never sent to the remote server unless specifically requested, didn’t require a third party add-on, and was big enough to hold useful information. And this was good.

HTML5 storage is currently supported in the latest version of every major browser, but as we discussed yesterday, you can check if it’s available using the Modernizr script and the Modernizr.localstorage bool. Your size can use up to 5 megabytes to store your information, though you unfortunately have to store it as strings, which can greatly expand the size of your data.

There are two storage options you can use: sessionStorage and localStorage. SessionStorage information will be lost when the window is closed, while localStorage info is permanent (until deleted). The code is fairly simple:

localStorage.setItem(‘itemname’, ‘data’); // define and set the variable

localStorage.getItem(‘itemname’); // return the data; notice that this isn’t a complete statement as you haven’t done anything with the data. A complete statement would be along the lines of

alert(“Your data is ” + localStorage.getItem(‘userdata’);

If you don’t need the data anymore, you can get rid of it withlocalStorage.removeItem(‘itemname’);

SessionStorage works the same way; just replace “local” with “session” in the code above. You can also store content in an SQLite database and use standard SQL inside of your script:

database.executeSql(SQL command) {
// do something with the results

As with cookies, local storage comes with some privacy concerns. Anyone putting content on multiple sites (most likely an advertiser) could use the store to track a user across multiple sessions, building a fairly detailed profile. As with cookies, the user has the option of refusing to allow data to be stored or expiring it after a given amount of time. Additionally, it may be possible to access another site’s information through spoofing if SSL is not used. One restriction to be aware of is that multiple pages on one hostname (e.g., free website hosting such as the now-defunct geocities) share a local storage object, so any page can access and overwrite information stored by other pages on the same host.

On a side note, Google previously implemented similar functionality with Google Gears, but they are now abandoning it in favor of the local storage and geolocation options in HTML5.