Use local storage and fall back to 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),
    if(!szExpires) // default expiration date : 1 year
        date = new Date();
        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,
    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:



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){
            return true;
    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."name","value"); // saves to the browser
Storage.get("name"); // prints "value"


There are no comments added yet.

Let's hear your thoughts

For my eyes only