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.
-
What browsers do you care about supporting? – Lukas Jan 10 '13 at 20:33
-
All the major ones would be nice, although I will understand if your method doesn't support IE. – Bluefire Jan 10 '13 at 20:35
5 Answers
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.

- 372,613
- 87
- 782
- 758
-
Is that dependent on the cache? I.e., if I clear my cache, will that be deleted? – Bluefire Jan 10 '13 at 20:36
-
In any browser, you can choose what you remove. But simply emptying the cache won't clear the local storage unless you ask for it. – Denys Séguret Jan 10 '13 at 20:38
-
Also, you wrote "only strings". Is it possible to store an array/object? – Bluefire Jan 10 '13 at 20:47
-
1@Bluefire It means you have to handle the serialization of other types. I added an example. – Denys Séguret Jan 10 '13 at 20:52
-
You have three options:
- Cookies: https://developer.mozilla.org/en-US/docs/DOM/document.cookie
- DOMStorage (sessionStorage or localStorage): https://developer.mozilla.org/en-US/docs/DOM/Storage
- If your users are logged in, you could persist data in your server's DB that is keyed to a user (or group)

- 16,426
- 3
- 48
- 55
-
For browser's storage, this is helpful: https://github.com/localForage/localForage – Akhorus Mar 14 '17 at 19:37
You could possibly create a cookie if thats allowed in your requirment. If you choose to take the cookie route then the solution could be as follows. Also the benefit with cookie is after the user closes the Browser and Re-opens, if the cookie has not been deleted the value will be persisted.
Cookie *Create and Store a Cookie:*
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
The function which will return the specified cookie:
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Display a welcome message if the cookie is set
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{
alert("Welcome again " + username);
}
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{
setCookie("username",username,365);
}
}
}
The above solution is saving the value through cookies. Its a pretty standard way without storing the value on the server side.
Jquery
Set a value to the session storage.
Javascript:
$.sessionStorage( 'foo', {data:'bar'} );
Retrieve the value:
$.sessionStorage( 'foo', {data:'bar'} );
$.sessionStorage( 'foo' );Results:
{data:'bar'}
Local Storage Now lets take a look at Local storage. Lets say for example you have an array of variables that you are wanting to persist. You could do as follows:
var names=[];
names[0]=prompt("New name?");
localStorage['names']=JSON.stringify(names);
//...
var storedNames=JSON.parse(localStorage['names']);
Server Side Example using ASP.NET
Adding to Sesion
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;
// When retrieving an object from session state, cast it to // the appropriate type.
ArrayList stockPicks = (ArrayList)Session["StockPicks"];
// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;
I hope that answered your question.

- 1,870
- 2
- 21
- 46
-
1Good until the ASP.NET example...while that's the server-side environment I use and generally like, it doesn't really address the needs of the OP's question very well...if at all. Clear your browser cookies and .NET will have no way to connect the browser instance to your server-side "session" – BLSully Jan 10 '13 at 21:01
-
1Agree, The server side example I provided, I think it should not be part of the answer since the OP did not mention if he is using ASP.NET all but I added just for the sake of info. – tam tam Jan 10 '13 at 21:05
-
the server side storage put the data in the Session . but how to we access the Session in javascript ? – Adams.H Jan 04 '14 at 05:57
check out my js lib for caching: https://github.com/hoangnd25/cacheJS
My blog post: New way to cache your data with Javascript
Features:
- Conveniently use array as key for saving cache
- Support array and localStorage
- Clear cache by context (clear all blog posts with authorId="abc")
- No dependency
Basic usage:
Saving cache:
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', null, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd',categoryId:2});
Retrieving cache:
cacheJS.get({blogId: 1,type: 'view'});
Flushing cache
cacheJS.removeByKey({blogId: 1,type: 'view'});
cacheJS.removeByKey({blogId: 2,type: 'view'});
cacheJS.removeByContext({author:'hoangnd'});
Switching provider
cacheJS.use('array');
cacheJS.use('array').set({blogId:1},'<h1>Blog 1</h1>')};

- 398
- 2
- 12
I have written a generic caching func()
which will cache any variable easily and very readable format.
Caching function:
function calculateSomethingMaybe(args){
return args;
}
function caching(fn){
const cache = {};
return function(){
const string = arguments[0];
if(!cache[string]){
const result = fn.apply(this, arguments);
cache[string] = result;
return result;
}
return cache[string];
}
}
const letsCache = caching(calculateSomethingMaybe);
console.log(letsCache('a book'), letsCache('a pen'), letsCache('a book'));

- 1,159
- 12
- 24