Friday, March 5, 2010

localStorage returns undefined value

When I have just started to work with localStoage without reading much about it I have created something like this
localStorage['key'] = 'value';
alert(localStorage['key']);
Result was great, and I got nice alert with 'value' on it.
Quite excited, i created functionality i wanted to have, created nice tests and found out that something is not great at all and after localizing error I have found out that similar piece of code is not working as good as previous.
localStorage['key'] = {test:'value'};
alert(localStorage['key'].test);

In this case, alert returned 'undefined', but not 'value', what was quite unexpected.
However this code
localStorage['key'] = {test:'value'};
alert(localStorage['key']);
says that I have nice '[object Object]'. I checked it a bit and had found that this script
localStorage['key'] = {test:'value'};
alert(typeof localStorage['key']);
says that my localStorage result is in fact 'string', which was quite unexpected, as it should be Object.
As it turned out, localStorage uses structured clone algorithm and whether because of this or for some other reason it converts my object into string, stores it as such and therefore looses all properties and values.
Finally, I have found easy way to solve this problem by converting my object into JSON string. Fortunately Firefox have native JSON coverter functions and everything can be done simply like
localStorage['key'] = JSON.stringify({test:'value'});
alert(JSON.parse(localStorage['key']).test);
In WRT there is no such nice lib, but it is possible to download it at json.org. And it can be nicely used like this:
widget.setPreferenceForKey(JSON.stringify({test:'value'}), 'key');
alert(eval(widget.preferenceForKey('key')).test);
There is small issue though. As you see JSON lib is used to convert object to string, but it was not able to convert string to object on my Nokia device. But this small eval hack still works great and I am getting my value as expected.

No comments:

Post a Comment