This post was written by Jeff Balogh. Jeff works on Mozilla’s web development team.

New in Firefox 3.5, localStorage is a part of the Web Storage specification. localStorage provides a simple Javascript API for persisting key-value pairs in the browser. It shouldn’t be confused with the SQL database storage proposal, which is a separate (and more contentious) part of the Web Storage spec. Key-value pairs could conceivably be stored in cookies, but you wouldn’t want to do that. Cookies are sent to the server with every request, presenting performance issues with large data sets and the potential for security problems, and you have to write your own interface for treating cookies like a database.

Here’s a small demo that stores the content of a textarea in localStorage. You can change the text, open a new tab, and find your updated content. Or you can restart the browser and your text will still be there.


The easiest way to use localStorage is to treat it like a regular object:

>>> localStorage.foo = 'bar'
>>> localStorage.foo
"bar"
>>> localStorage.length
1
>>> localStorage[0]
"foo"
>>> localStorage['foo']
"bar"
>>> delete localStorage['foo']
>>> localStorage.length
0
>>> localStorage.not_set
null

There’s also a more wordy API for people who like that sort of thing:

>>> localStorage.clear()
>>> localStorage.setItem('foo', 'bar')
>>> localStorage.getItem('foo')
"bar"
>>> localStorage.key(0)
"foo"
>>> localStorage.removeItem('foo')
>>> localStorage.length
0

If you want to have a localStorage database mapped to the current session, you can use sessionStorage. It has the same interface as localStorage, but the lifetime of sessionStorage is limited to the current browser window. You can follow links around the site in the same window and sessionStorage will be maintained (going to different sites is fine too), but once that window is closed the database will be deleted. localStorage is for long-term storage, as the w3c spec instructs browsers to consider the data “potentially user-critical”.

I was a tad disappointed when I found out that localStorage only supports storing strings, since I was hoping for something more structured. But with native JSON support it’s easy to create an object store on top of localStorage:

Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}
 
Storage.prototype.getObject = function(key) {
    return JSON.parse(this.getItem(key));
}

localStorage databases are scoped to an HTML5 origin, basically the tuple (scheme, host, port). This means that the database is shared across all pages on the same domain, even concurrently by multiple browser tabs. However, a page connecting over http:// cannot see a database that was created during an https:// session.

localStorage and sessionStorage are supported by Firefox 3.5, Safari 4.0, and IE8. You can find more compatibility details on quirksmode.org, including more detail on the storage event.

19 comments

Post a comment
  1. Mike Beltzner wrote on June 25th, 2009 at 9:47 pm:

    Huh. I hadn’t thought of just stringifying/parsing JSON like that. And I bet with native JSON support, that goes pretty darned quickly, doesn’t it?

    Awesome post.

    Reply

  2. Pingback from 颠覆网络35天 ─ 使用localStorage保存数据 < MJiA on June 25th, 2009 at 11:24 pm:

    [...] 原文地址:saving data with localStorage 系列地址:颠覆网络35天 [...]

    Reply

  3. Theodora Vorbix wrote on June 26th, 2009 at 11:01 am:

    I’ve been hacking localStorage for some time and it can completely replace sqlite if only it managed collections natively.

    Right now we can save localStorage.user=”john”

    It would be cool if we could also save localStorage.user[0] = “jane”

    Right now we can not, but with an easy hack it can be done.

    I’ve tested it with hundreds of records and it works fine.

    Please consider handling collections in localStorage for firefox.next

    Reply

  4. Theodora Vorbix wrote on June 26th, 2009 at 12:23 pm:

    Here, some tests with collections:

    http://georgenava.googlepages.com/localstorage.html

    Reply

  5. Al wrote on June 26th, 2009 at 4:31 pm:

    Goodbye cookies! (I won’t miss you.)

    Reply

  6. Shane wrote on June 27th, 2009 at 8:13 am:

    Al, I don’t think this is going to replace cookies. Localstorage is exactly that, local. I don’t think it goes back to the server so you couldn’t use it for things like maintaining logins. You’d still need cookies for that. (Though, I guess you could send the localstorage data using XHR but why, when cookies do the job just fine and hold the same data?)

    Reply

  7. bd_ wrote on June 29th, 2009 at 6:43 am:

    How can the user clear this data? AFAICS, clearing cookies or using the “clear recent history” don’t work…

    Reply

  8. foobar wrote on June 29th, 2009 at 11:56 am:

    Yay more crap on my harddrive. Cookies were bad enough.

    Reply

  9. Tom Chiverton wrote on June 30th, 2009 at 6:43 am:

    “I don’t think this is going to replace cookies”
    Nope, esp. as the linked QuirksMode blog post is full of ‘browser X does Y, but browser A does B, browser W only tells you K’ etc. etc.

    Reply

  10. Trackback from Annals of the Homestarmy on June 30th, 2009 at 7:37 am:

    Firefox 3.5…

    Tuesday should see the
    release of Firefox 3.5, which has a lot of exciting features I hope to be able to take advantage of from this blog -
    including using localStorage to implement
    the “Auto-save” feature, which should cut down on a lot of the un-pu…

    Reply

  11. Pingback from saving data with localStorage | the life of a web developer on July 2nd, 2009 at 4:07 am:

    [...] Its written by Jeff Balogh, part of the Mozilla web development team Link : http://hacks.mozilla.org/2009/06/localstorage/ [...]

    Reply

  12. lunter wrote on August 3rd, 2009 at 2:40 am:

    IE8: Storage.prototype does not work

    Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
    }

    Storage.prototype.getObject = function(key) {
    return JSON.parse(this.getItem(key));
    }

    Reply

  13. lrbabe wrote on August 8th, 2009 at 4:44 pm:

    It’s even possible to store images in localStorage by combining the use of drawImage and toDataUrl of a canvas.
    There is however a limit size to any localStorage.

    Reply

  14. Pingback from 谋智社区 » Blog Archives » 颠覆网络35天 ─ 使用localStorage保存数据 on August 13th, 2009 at 9:32 pm:

    [...] 原文地址:saving data with localStorage 系列地址:颠覆网络35天 [...]

    Reply

  15. Pingback from Recommendations, Collections, and Contributions (oh my!) « Mozilla Add-ons Blog on August 28th, 2009 at 12:28 am:

    [...] also added a treat for users of browsers that support localStorage (including Firefox 3.5): recently viewed collections. When browsing through the collection [...]

    Reply

  16. Pingback from AMO 5.0.9 Launched! :: The Mozilla Blog on August 28th, 2009 at 9:53 am:

    [...] also added a treat for users of browsers that support localStorage (including Firefox 3.5): recently viewed collections. When browsing through the collection [...]

    Reply

  17. Pingback from bunnyhero dev - Twitter follower tracker on September 18th, 2009 at 8:42 pm:

    [...] thanks to Twitter’s handy “callback” parameter in JSON responses. I use the localStorage property, supported in some modern browsers, to remember the user’s follower history. [...]

    Reply

  18. Pingback from Offline Cross-Browser Client-Side Storage for the Web using JavaScript and a little Flash | AddyOsmani.com | Where Web Businesses Grow on October 21st, 2009 at 8:46 pm:

    [...] was putting into discovering the best way to achieve offline client-side storage using FireFox’s LocalStorage, HTML5’s local databases and Chrome’s Google Gears. Projects such as PersistJS have tried to [...]

    Reply

  19. Pingback from Offline Cross-Browser Client-Side Storage for the Web using JavaScript and a little Flash « BrightSpark on December 6th, 2009 at 10:42 am:

    [...] putting into discovering the best way to achieve offline client-side storage using FireFox’s LocalStorage, HTML5’s local databases and Chrome’s Google Gears. Projects such as PersistJS have [...]

    Reply

Add your comment