Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  107] [ 7]  / answers: 1 / hits: 158441  / 12 Years ago, thu, january 10, 2013, 12:00:00

What I want to do is to be able to create a variable, give it a value, close and reopen the window, and be able to retrieve the value I set in the last session. What is the simplest way to do that? JQuery answers are welcome.


More From » jquery

 Answers
20

Use localStorage for that. It's persistent over sessions.



Writing :



localStorage['myKey'] = 'somestring'; // only strings


Reading :



var myVar = localStorage['myKey'] || 'defaultValue';


If you need to store complex structures, you might serialize them in JSON. For example :



Reading :



var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};


Writing :



localStorage['myKey'] = JSON.stringify(myVar);


Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.



Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.


[#80956] Wednesday, January 9, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cruzjenseny

Total Points: 409
Total Questions: 93
Total Answers: 106

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
;