0

I want to replace my current functions of creating and reading cookie, and save it into the local storage instead. How can I replicate this for local storage instead?

function createCookie(name, value, days) {



    var c_date,
    c_name = name + "=" + value + ";",
    c_expi = "",
    c_domain = "domain=.domain.com;",
    c_path = "path=/";

    if (days > 0) {
        c_date = new Date();
        c_date.setTime(c_date.getTime() + (days * 24 * 60 * 60 * 1000));
        c_expi = "expires=" + c_date.toGMTString() + ";";
    }

    // create the cookie
    document.cookie = c_name + c_expi + c_domain + c_path;

}

    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }
EnexoOnoma
  • 8,454
  • 18
  • 94
  • 179

2 Answers2

1

Using a LocalStorage is to easy then store a cookie value .. you need to just write

// Store
localStorage.setItem("lastname", "Smith");   // here is lastname is your key
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");

If you want to check that Browser support local Storage then .

 if(typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.
} else {
    // Sorry! No Web Storage support..
}

but before use localStoreage you must read HTML 5 Storage's same origin policy

Community
  • 1
  • 1
Anant Dabhi
  • 10,864
  • 3
  • 31
  • 49
1

you can also store javascript object as JSON

function createCookie(name, value, days) {
    var c = {
        domain = ".domain.com",
        path = "path=/"
    }
    c[name] = value;

    if (days > 0) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        c.expi = date.toGMTString();
    }

    //local storaage
    localStorage.setItem('somename', JSON.stringify(c));

}

function readCookie(name) {
    var c = JSON.parse(localStorage.getItem('somename') || '{}');
    return c[name];
}
Ja9ad335h
  • 4,995
  • 2
  • 21
  • 29