Cookie manipulation through JavaScript

Posted By  amalhashim On 06 Apr 2010 10:04:39
emailbookmarkadd commentsprint
No of Views:606
Bookmarked:0 times
Votes:0 times

Introduction

In this tips, to help write and read cookies with javascript

 

Code Snippet

<script type="text/javascript">
    currentuser = "amal"
    window.onload=function() {
        if (navigator.cookieEnabled) {
            var username = readCookie("username");
            if (username) {                
                alert("cookie name = " + username);
                if (username != currentuser) {
                    eraseCookie(username);
                } else {
                    setCookie("username",username);
                }
            } else {
                alert("setting cookie");
                setCookie("username", currentuser);
            }
        }
    }
    
    // set cookie expiration date in year 2010
    function setCookie(key,value) {
        var cookieDate = new Date(2010,11,10,19,30,30);
        document.cookie=key + "=" + encodeURI(value) + "; expires=" + 
        cookieDate.toGMTString() + "; path=/";
    }
    
    // each cookie separated by semicolon;
    function readCookie(key) {
        var cookie = document.cookie;
        var first = cookie.indexOf(key+"=");

        // cookie exists
        if (first >= 0) {
            var str = cookie.substring(first,cookie.length);
            var last = str.indexOf(";");

            // if last cookie
            if (last < 0) last = str.length;

            // get cookie value
            str = str.substring(0,last).split("=");
            return decodeURI(str[1]);
        } else {
            return null;
        }
    }
    
    // set cookie date to the past to erase
    function eraseCookie (key) {
        var cookieDate = new Date(2000,11,10,19,30,30);
        document.cookie=key + "= ; expires="+cookieDate.toGMTString()+"; path=/";
    }

</script>

Thank you

Sign Up to vote for this article
Other popular Tips/Tricks
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top