Saturday, November 18, 2017

JavaScript functions to handle cookies


Here are the functions to handle cookies using JavaScript.

    function SetCookie(cookieName, cookieValue, exdays) {
        let d = new Date();
       d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        let expires = "expires=" + d.toUTCString();
        document.cookie = cookieName+ "=" + cookieValue+ "; " + expires;
    }

    function GetAllCookie() {
        return document.cookie;
    }

    function DelCookie(cname) {
        let name = cname + "=";
        document.cookie = cname + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
        return "";
    }

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


No comments:

Post a Comment

All Blogs so far ...