saving data with localStorage

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.


37 comments

  1. Mike Beltzner

    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.

    June 25th, 2009 at 21:47

    1. Chris McKee

      Last test i saw showed that eval parsed the JSON faster… thatll change as the code gets cleaned up for fulltime use

      http://jsperf.com/json-parsing/12

      August 20th, 2010 at 16:51

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

    June 25th, 2009 at 23:24

  3. Theodora Vorbix

    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

    June 26th, 2009 at 11:01

  4. Theodora Vorbix

    Here, some tests with collections:

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

    June 26th, 2009 at 12:23

  5. Al

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

    June 26th, 2009 at 16:31

  6. Shane

    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?)

    June 27th, 2009 at 08:13

  7. bd_

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

    June 29th, 2009 at 06:43

    1. ant

      delete persistent storage

      December 15th, 2010 at 00:10

  8. foobar

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

    June 29th, 2009 at 11:56

  9. Tom Chiverton

    “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.

    June 30th, 2009 at 06:43

  10. 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…

    June 30th, 2009 at 07:37

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

    July 2nd, 2009 at 04:07

  12. lunter

    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));
    }

    August 3rd, 2009 at 02:40

  13. lrbabe

    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.

    August 8th, 2009 at 16:44

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

    August 13th, 2009 at 21:32

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

    August 28th, 2009 at 00:28

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

    August 28th, 2009 at 09:53

  17. […] 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. […]

    September 18th, 2009 at 20:42

  18. […] 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 […]

    October 21st, 2009 at 20:46

  19. […] 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 […]

    December 6th, 2009 at 10:42

  20. Amos

    According to the HTML5 spec, the storage objects should support persisting any javascript objects, not just String types. However, this doesn’t seem to be the case with the FF3.5 implementation (hence the JSON hack in the article).
    Why was this partially implemented?

    February 10th, 2010 at 06:42

  21. james

    Simple functionality – well explained – I am looking to link it in with some graphics where the filament group have done some nice work on canvas and then find a way of syncing the local storage with server based data – Should be simple and really handy for keeping user storage limits under control

    February 18th, 2010 at 13:00

  22. Sid Maestre

    Thanks! I”m working on an HTML/CSS/JQuery iPhone app and looking to save an object to localStorage. You’re tip on saving a JSON object worked like a charm.

    March 17th, 2010 at 07:58

  23. HM

    Does this only work on hosted sites? I can’t get it to remember even after a refresh (pressing F5).

    The file is:
    file:///home/me/workspace/course/test.htm

    The content of the file is:
    hi

    document.getElementById(“out”).value = localStorage.lesson;
    function setStorage(){
    localStorage.lesson=document.getElementById(“in”).value;
    document.getElementById(“out”).value = localStorage.lesson;
    }

    I press the button and the other textarea is set, press F5 and localStorage.lesson is null.

    This is in 3.5.9 for linux mint

    May 15th, 2010 at 03:33

  24. Daniel O’Connor

    Annoyingly, Chrome raises “uncaught illegal access” exceptions if localStorage isn’t populated for the given key.

    A better way might be to do:

    /**
    * Firefox workaround – serialize objects as JSON
    *
    * @see http://hacks.mozilla.org/2009/06/localstorage/
    */
    Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
    };

    /**
    * Firefox workaround – unserialize objects from JSON
    *
    * @see http://hacks.mozilla.org/2009/06/localstorage/
    */
    Storage.prototype.getObject = function(key) {
    try {
    return JSON.parse(this.getItem(key));
    } catch (e) {
    return null;
    }
    };

    June 3rd, 2010 at 20:04

  25. […] HTML5 localStorage: 브라우저가 재시작되어도 이미지 데이터를 저장한다. […]

    July 7th, 2010 at 09:04

  26. sofish

    i typed “hmmm…” in the 1st <textarea> , then copy the URL of this page, and open it in a new tab… there, the 1st <textare> give me the “answer”: undifined. tested in Fx 3.6.6

    July 12th, 2010 at 19:06

  27. Oscar Godson

    Just a question, why can’t we use this locally when the URL protocol is file://? I spent about an hour troublshooting and there is really no reason why

    July 21st, 2010 at 15:40

  28. David Laurell

    @Oscar Godson
    Maybe because localStorage is limited to the domain and when you are viewing the page locally you don’t have a domain?

    You have maybe figured it out by now, but anyone else might want to know the answer.

    October 8th, 2010 at 07:59

  29. Mozilla Hacker

    To get rid of localStorage on Windows, close Firefox, then navigate to %USERPROFILE%Application DataMozillaFirefoxProfiles[some random string].default. In that directory, delete sessionstore.*

    For other operating systems, type a unique string into the demonstration window above, and then use “grep -rli .” in a shell to find the location of your sessionstore.js. The file is apparently filled in realtime.

    I’ve only just discovered localStorage, and it’s already full of tons of unwanted tracking data.

    October 9th, 2010 at 20:46

    1. Mozilla Hacker

      I must amend my previous post: You must also delete webappstore.sqlite, or else sessionstore.js can be restored from it.

      October 9th, 2010 at 20:52

  30. phil

    Hi all,

    Before you replace your cookies (if some use this bad stuff) by localStorage, you have to know you might experience troubles and hacking issues on hosted sites.

    When you write a cookie, you can set the PATH in order other users pages won’t be able to read it.
    As localStorage is per site (domain) pages of other users on the same hosting server will be able to read and even update your entries in the localStorage.

    So localStorage can be great but you must use it cleverly ;o)

    November 9th, 2010 at 12:17

    1. Steve

      Hi Phil,

      Are you confusing $_SESSION and $_COOKIE serverside variables with localStorage which is strictly clientside only

      December 12th, 2010 at 18:27

  31. […] http://hacks.mozilla.org/2009/06/localstorage/ […]

    June 2nd, 2011 at 00:36

  32. […] el mapa de juego más amplio del mundo sin ralentizar el interface de la home del usuario; localStorage, que continuamente salva el progreso de los personajes de los y HTML5 […]

    April 12th, 2012 at 15:26

  33. Noe Dadon

    Example of usage:

    window.localStorage.setObject(‘obj’,{name:’math’,description:’mathDescription’})

    window.localStorage.getObject(‘obj’);

    February 5th, 2013 at 02:32

Comments are closed for this article.