How can I store a cookie in local storage with Javascript?

17,681

Solution 1

Have a look at http://diveintohtml5.info/storage.html. The history might not be very interesting at all, but it at least provides an excellent link list to other tutorials in the further-reading section.

So, now to your code. The first thing to mention is that localStorage has no expire - it's persistent (until the user manually cleans everything). If you'd like to use some shorter storage, you might also use sessionStorage, which has the same interface but last only until the browser is closed.

Rephrasing your code is simple:

function getCookie(c_name) {
    return localStorage.getItem(c_name);
}

function setCookie(c_name, value, expiredays) {
    return localStorage.setItem(c_name, value);
}

Solution 2

I used the information in the other answers, so this isn't a different answer, but I just thought it would be helpful to others to see the complete code I ended up with. This can be pretty much dropped in as a replacement for using cookies (as I did). It tests for local storage, and uses that if present, and uses cookies if it isn't.

Note you'll probably want to take out the alerts when implementing it.

function getCookie(c_name)
{
    if(typeof localStorage != "undefined")
    {
        return localStorage.getItem(c_name);
    }
    else
    {
        var c_start = document.cookie.indexOf(c_name + "=");
        if (document.cookie.length > 0)
        {
            if (c_start !== -1)
            {
                return getCookieSubstring(c_start, c_name);
            }
        }
        return "";
    }
}

function setCookie(c_name, value, expiredays)
{
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    if(typeof localStorage != "undefined")
    {
        alert("This place has local storage!");
        localStorage.setItem(c_name, value);
    }
    else
    {
        alert("No local storage here");
        document.cookie = c_name + "=" + escape(value) +
        ((expiredays === null) ? "" : ";expires=" + exdate.toUTCString());
    }
}

Solution 3

localStorage behaves exactly like a regular Object.

localStorage.somekey = "My data"; // set
alert(localStorage.somekey); // get
delete localStorage.somekey; // unset

The only real difference between localStorage and any other Object is that it is pesistent. Any page from the same origin can access the values in the object, and they even survive if the browser is closed.

They are superior to cookies in every way for data storage, because they don't get sent to the server with every single request (although that's not to say cookies are useless - both have their advantages).

It's really simple ;)

Share:
17,681
Questioner
Author by

Questioner

Updated on June 26, 2022

Comments

  • Questioner
    Questioner almost 2 years

    I have an app for Android (and hopefully later iPhone) that is based on Javacript and is made into an app using Phonegap/Applaud.

    Unfortunately, setting and getting cookies is not working on Android, and this might be particular to the Android environment. I was advised that using "local storage" might be more reliable.

    However, I knew nothing about local storage until this morning, and so I'm struggling to get aquainted. From what I gather, it's basically just another place to save data with a different syntax. For my situation, I don't think it gives me any advantages over cookies other than the fact that Android is forcing me to use it. As a result, I'm hoping I can still leverage my existing code for setting and getting cookies, and not have to take on a whole new approach.

    Surely I can just do a test in my Javascript to see if there is local storage, and if so, store and retrieve my cookie data there, and if not, then just use cookies as normal?

    Note 1: I searched Stack Overflow for similar questions, and there was this one which at first seems exactly what I'm talking about, but it's too terse so I can't parse it to know what I should do with it. Also, I think it assumes the presence of libraries and code that I don't think I have. I also looked at this question but I think it's doing the reverse of what I'm after.

    Note 2: This is my current code for getting and setting cookies (procured from somewhere on the web. Up until the Android problem, was rock solid reliable):

    function getCookie(c_name)
    {
        var c_start = document.cookie.indexOf(c_name + "=");
    
        if (document.cookie.length > 0)
        {
            if (c_start !== -1)
            {
                return getCookieSubstring(c_start, c_name);
            }
        }
        return "";
    }
    
    function setCookie(c_name, value, expiredays)
    {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + expiredays);
            document.cookie = c_name + "=" + escape(value) +
            ((expiredays === null) ? "" : ";expires=" + exdate.toUTCString());
            alert("this is document.cookie: " + document.cookie);
    }