Tuesday, March 13, 2012

Storing JavaScript objects in HTML5 localStorage

Using HTML5, web pages can store data locally within the user's browser. Earlier, this was done with cookies. However, HTML5 local storage is more secure and faster. Also, the stored data is not included with every server request, but used only when asked for. Therefore large amounts of data can be saved without affecting a website's performance.

The data is stored in key/value pairs. The following JavaScript example saves a book title locally:
localStorage.setItem("bookTitle", "My Book Title");

Recently I wanted to save an array of objects and discovered that this can be done using JSON and some helper methods. Here is the JavaScript code to store the array:
var books = [
    { title: "First title", author: "First author" },
    { title: "Second title", author: "Second author" }
localStorage.setItem("books", JSON.stringify(books));
And the following code reads the book data from local storage when you need it:
var books = null;
var json = localStorage.getItem("books");
if (json) {
    books = JSON.parse(json);
Note that a web page can only access data stored by itself. HTML5 local storage is supported in all major browsers.

No comments:

Post a Comment