How to set, get and delete a cookie in Javascript

Dung Do Tien Apr 10 2020 189

I have written an application web with a login form But I want remember account when users log on and I think about cookie but I don't know how to get and set it. I need some functions to do it. (Add, get and delete)

I need any suggestions. Thanks, many

Have 1 answer(s) found.
  • Cookies are data, they are small items of data and store, each consisting of a name and a value. They are store on your computer. When a web server has sent a web page to a browser. In Javascript to has support cookie through document.cookie object:

    let make an example create a cookie with a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

    document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/"; 
    

    To manipulate easily with a cookie I make some function to read, create and delete cookie as below. 

    1. Add a Cookie

     function add_cookie(cname, cvalue, exdays) {
    	var d = new Date();
    	d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    	var expires = "expires=" + d.toUTCString();
    	var domain = location.hostname.split('.').reverse()[1] + "." + location.hostname.split('.').reverse()[0];
    	if (domain != undefined && domain.indexOf("localhost") > - 1) domain = "localhost";
    	document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/;domain=." + domain;
    } 
    

    In this function, we have some domain to set some info to the cookie:

    - cname : key of the cookie

    - expires: Time cookie will be destroyed ( maybe understood delete)

    - path : url store cookie, If not specified, defaults to the current path of the current document location. In this case I set default all to "/";

    - domain: domain of website will store cookie, I have been add more dot(.) of before value to help manipulate with both main and subs domain.

     

    2. Read a cookie

    read_cookie: function (cname) {
    	var name = cname + "=";
    	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);
    		}
    		if (c.indexOf(name) == 0) {
    			return c.substring(name.length, c.length);
    		}
    	}
    	return "";
    } 
    

    As you know the cookie store by a pair of key & value, so to read a cookie you only get by key to read value.

     

    3. Delete a cookie

    To delete a cookie you only need set expire time is less than current date. Use the function of add a cookie.

     

    All Together Now

    You should aggregate them into an object for ease of use and reuse and all you need is below :

    var cookie_manager = cookie_manager || {};
    cookie_manager = {
        add_cookie: function (cname, cvalue, exdays) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
            var expires = "expires=" + d.toUTCString();
            var domain = location.hostname.split('.').reverse()[1] + "." + location.hostname.split('.').reverse()[0];
            if (domain != undefined && domain.indexOf("localhost") > - 1) domain = "localhost";
            document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/;domain=." + domain;
        },
        read_cookie: function (cname) {
            var name = cname + "=";
            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);
                }
                if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                }
            }
            return "";
        }
    }; 

    This is all custom about cookie for you. but you also using some libraries support for cookie very useful.

    Look like Jquery cookie 

    I hope this info helpful to you.

    Sandeep Kumar Apr 11 2020
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips