Was wondering whether there are other ways of retaining an object variable after page refresh besides using session and cookie. Tried window.name
but the value become undefined after page refresh. The localStorage
is good but too bad it only store in string value instead of object value.
Asked
Active
Viewed 684 times
0
-
There's already some other discussions about this. I don't think the conclusion/discussion has or will change soon since HTTP is stateless. Either you persist the data somewhere else, or when your page reloads from the server, the server puts something in the HTML/JS http://stackoverflow.com/questions/16206322/how-to-get-js-variable-to-retain-value-after-page-refresh hint - yes `localStorage` is what most would suggest – Don Cheadle May 24 '16 at 16:08
2 Answers
1
You could serialise the object and store in localStorage
. Then when you want to use it again, you unserialise it. Here's an example:
var myObject = {
"Hello": "World",
"Foo": "Bar"
}
localStorage.setItem("myObject", JSON.stringify(myObject));
Then later on, you can retrieve the object from localStorage
:
var myObject = JSON.parse(localStorage.getItem("myObject"));
For more information, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Sam
- 893
- 8
- 21