0

I'm trying to implement local storage for navigating by pages.

I have a web site with some pages, all in one folder.

In one page, I'm setting the local storage:

var myObject = { 'id': 1, 'price': 50.0, 'total': 3 };
localStorage.setItem('data', JSON.stringify(myObject));

While in the first page, I see the local storage with data- thats OK. But after navigating to the second page, I see that the local storage is empty while trying to read:

var localObject = localStorage.getItem('data');

Can't understand where is the problem.

Puck
  • 2,080
  • 4
  • 19
  • 30
oleg
  • 131
  • 2
  • 9
  • 1
    Don't forget to `JSON.parse` the `localObject`! – Ian Jun 18 '13 at 14:15
  • So you are doing `console.log(localObject)` and you are not getting the string? – epascarello Jun 18 '13 at 15:07
  • Yeah, get :"ReferenceError: localObject is not defined" – oleg Jun 18 '13 at 15:13
  • 1
    Please show us the exact URLs used to access the two pages. Also what browser are you using? This related question, http://stackoverflow.com/questions/16010827 , shows that the value should be `null` if the item does not exist which makes me think your domains are somehow different. Though even then you should receive `null` not `undefined`. In the case of a security violation you should get a hard error thrown. Curious. – HBP Jun 18 '13 at 15:57

1 Answers1

2

You are not showing much of the code, but localStorage won't throw a reference error if an item does not exist.

It does not matter if you navigated to another domain as the localStorage would just return null when using getItem (undefined if you used localStorage[key]).

This indicates that you have a problem elsewhere in the code not directly related to localStorage.

But you need to show a bit more code and tell us what line the error occur on.

Also as stated in the comments, you would need to JSON.parse the data to re-create the object you stringify'ed.