16

I trief to use the localStorage object in Phonegap, but instead of getting an object, the getItem only receives a string "[object Object]":

var storage = window.localStorage;
storage.setItem('test',{'name':'mark','greeting':'Hello'});
console.log(storage.getItem('test'));

In the console of Google chrome it says:

[object Object]

The output of "console.log(storage)" is the following:

Storage
...
test: "[object Object]"

If I try to access a property of the object it just says "undefined":

storage.getItem('test').name

Any ideas how to get this to work?

Gareth
  • 133,157
  • 36
  • 148
  • 157
hering
  • 1,956
  • 4
  • 28
  • 43
  • Are you sure the console isn't just **displaying** [object Object]? What does `console.log(storage.getItem('test').name)` show? – RoToRa Apr 01 '11 at 13:52
  • Just found this: http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage – RoToRa Apr 01 '11 at 14:23
  • 1
    When you try to store anything other than strings, setItem will call ".toString()" on it, which in your case is "[object Object]". Do what Martinj says below, stringify it first. Furthermore, this has nothing to do with PhoneGap, but is a UIWebview/Webkit issue. – Shazron Apr 01 '11 at 16:14

1 Answers1

39

HTML5 localStorageallows you to store strings only.

You'll have to perform a JSON.stringify when you store your object, and JSON.parse when you retrieve it.

Matt
  • 74,352
  • 26
  • 153
  • 180
Martijn
  • 13,225
  • 3
  • 48
  • 58
  • 1
    Im using dojo and did dojo.toJson and dojo.fromJson – blong824 Jan 25 '12 at 19:20
  • The stringify and parse approach is worth gold. But on Android (testing in in-app browser on 2.3.3 on Samsung), the following error occurs: "Web Console(5504): Uncaught illegal access at file:///android_asset/www/"etc if I try this: JSON.parse(localStorage.getItem('purchases')) – Wytze Nov 04 '13 at 20:43
  • @Wytze: does the error also occur if you just do `localStorage.getItem('purchases')`, without the JSON.parse? Because "illegal access" sounds like the problem lies with localStorage, not with JSON. – Martijn Nov 05 '13 at 08:52
  • 1
    Thanks Martijn. Turns out the error occurred if the item was still empty. LocalStorage.getItem('purchase') would return null, and that would cause JSON.parse to throw the illegal access error. – Wytze Nov 06 '13 at 10:43