Cookies
There are better ways to save information on the browser then using cookies. Cookies save all values in one long string and has to be parsed every time you need to retrieve a value. The way cookies work is that they become part of the HTTP Request. Every time you make a request all the data is transferred from one page to the other. The data is available through the document.cookie
API.
You have a limit of 4KB that has to be shared with all other scripts. Here is how it works:
document.cookie = "propname=value;";
Cookies can take more arguments, like the expiration date, path, domain, and a security flag. Usually setting cookies is abstracted with function like this:
// save a value
setCookie = function(szName, szValue, szExpires, szPath, szDomain, bSecure) {
var szCookieText = escape(szName) + '=' + escape(szValue),
date;
if(!szExpires) // default expiration date : 1 year
{
date = new Date();
date.setTime(date.getTime()+(365*24*60*60*1000));
szExpires = date.toGMTString();
}
szCookieText += (szExpires ? '; EXPIRES=' + szExpires : '');
szCookieText += (szPath ? '; PATH=' + szPath : '');
szCookieText += (szDomain ? '; DOMAIN=' + szDomain : '');
szCookieText += (bSecure ? '; SECURE' : '');
document.cookie = szCookieText;
};
// retrieve a value
getCookie = function(szName){
var szValue = null,
cookie = document.cookie,
arr,arr2;
if(cookie){ //only if exists
arr = cookie.split((escape(szName) + '='));
if(2 <= arr.length){
arr2 = arr[1].split(';');
szValue = unescape(arr2[0]);
}
}
return szValue;
};
It can be used now like this:
setCookie("name","value");
LocalStorage
The alternative is to use localStorage. It uses a key value pair just like cookies, but does not have the limitation of 4 KB, instead you have 5MB. It is not supported in older browsers like IE7. You can write a function that falls back to cookies if it's not supported.
Storage = {
save: function (key,value){
if (window.localStorage){
localStorage.setItem(key,value);
return true;
}
setCookie(key,value);
},
get: function(key) {
if (window.localStorage){
return localStorage.getItem(key);
}
return getCookie(key);
}
}
Now we can use the Storage object to save a retrieve values.
Storage.save("name","value"); // saves to the browser
Storage.get("name"); // prints "value"
Sign up for the Newsletter.
Comments(1)
Gh61 :
The getCookie method is not working properly.
If you have document.cookie = 'b=neco; atlas=555; ba=333; a=' and call getCookie('a'), you get '333' as value. But that's the value of 'ba' cookie.
Let's hear your thoughts