JavaScript – How To Save an Object in Cookie

This example is going to show you how to save a JavaScript Object in Cookie.

 

1. Define setCookie() and getCookie() functions:

cookie.js
function getCookie(cname) {
    var name = cname + '=';
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return '';
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = 'expires='+ d.toUTCString();
    document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
}

2. To save an Object in cookie

We first need to convert the Object to JSON string by using JSON.stringify() function. And use the JSON.parse() function to parse the saved JSON string in cookie to the Object again. See the following code for more details:

app.js
/// 1. Save a object in cookie
var user = {
	name: 'David',
	age: 18,
	gender: 'male'
};

// convert the user object to JSON string using JSON.stringify() function var userJsonString = JSON.stringify(user); // save the the json string in session setCookie('user_info', userJsonString, 7); /// 2. Read the saved user info from cookie var savedUserJsonString = getCookie('user_info'); if (savedUserJsonString.length === 0) { // no user in cookie return; } // convert the saved user info to JSON object using JSON.parse() function var savedUser = JSON.parse(savedUserJsonString); // finally, display the user info in the view or console console.log('name: ', savedUser.name); // David console.log('age: ', savedUser.age); // 18 console.log('gender: ', savedUser.gender); // male 

0 0 vote
Article Rating
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ben Challenor
Ben Challenor
2 years ago

Thanks. It saves me a lot of time.

1
0
Would love your thoughts, please comment.x
()
x