Saturday, November 12, 2011

JQuery - Destroy the cookies on browser close.

Challenge

Trying to destroy the cookies once the browser is closed. I tried a lot to find on internet doing that same thing using C# but finally i figured out using JQuery.



Solution

Please try the below given block to make this work. I found this on internet somewhere i forgot the place so using this same block.
<html>
<head>
    <title>Starting Cookie Page</title>
    <script type="text/javascript">
        function createCookie(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        }

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

        function eraseCookie(name) {
            createCookie(name, "", -1);
        }
    </script>
    <script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body onload="
$(document).ready(function() {alert('loaded');});">
    <p>
        <button onclick='createCookie("ccSiteVisited", "1", "");'>
            Create Cookie</button>
        <button onclick='alert(readCookie("ccSiteVisited"));'>
            Read Cookie</button>
        <button onclick='eraseCookie("ccSiteVisited");'>
            Erase Cookie</button>
    </p>
    <p>
        Please note that once you set the cookie, that the cookie is maintained in all further
        browser instances you start.</p>
    <p>
        However, if you close all IE browsers and revisit page, you will see that cookie
        is NOT maintained.</p>
</body>
</html>

No comments:

Post a Comment