Thursday 16 February 2017

Javascript:Set cookie and get cookie


This post helps you to create , read and delete cookie in javacript.

Create Cookie:-
Below function is used to create cookie in JavaScript.

name-cookie name

value-value stored in cookie

expires-optional, set expiry time , if not specify, cookie is deleted when browser is closed.

path-optional, what path to the directory the cookie belongs to, if not specify cookie is belongs to current path.

domain-Optional. Specifies the domain of your site,If not specified, the domain of the current document will be used

secure-Optional. Tells the browser to use a secure protocol (https) for sending the cookie to the server


function setCookie(name, value, expires, path, domain, secure) {
    cookieStr = name + "=" + escape(value) + "; ";

    if (expires) {
        expires = setExpiration(expires);
        cookieStr += "expires=" + expires + "; ";
    }
    if (path) {
        cookieStr += "path=" + path + "; ";
    }
    if (domain) {
        cookieStr += "domain=" + domain + "; ";
    }
    if (secure) {
        cookieStr += "secure; ";
    }

    document.cookie = cookieStr;
}
function setExpiration(cookieLife) {   
    var today = new Date();
    var expr = new Date(today.getTime() + cookieLife * 24 * 60 * 60 * 1000);
    return expr.toGMTString();
}





Get/Read Cookie:- 
Below function is used to get/read cookie

function getCookie(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 "";
}

Delete Cookie:- 
Below function is used to get/read cookie


function del_Cookie(c_name) {
    if (getCookie(c_name))
  document.cookie = c_name + "=" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}



Example :-


setCookie("ck1", "value1", 120, '/');//without domain,non secure cookie
setCookie("ck2", "value2", 120, '/','www.abc.com',true);



No comments:

Post a Comment