OiO.lk Blog javascript How Can I Clear Cookies for my Web Application Using Javascript?
javascript

How Can I Clear Cookies for my Web Application Using Javascript?


I have an ASP.NET web application built with .NET Framework 4.6.2. This application logs users into their accounts for a separate engineering application to display data in a web interface. When users click a logout button, they are redirected to a logout page. Behind the scenes, their session for the engineering application is cleared. However, I also need to clear the cookies for the web application when the logout page loads.

The first thing I did was determine what path the cookies for my website were being stored. They were being stored in the / path.

Next, I added the following javascript to my logout.aspx page:

<script type="text/javascript">
    function deleteCookie(name) {
        document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
    }

    function clearAllCookies() {
        const cookies = document.cookie.split(';');
        cookies.forEach(cookie => {
            const cookieName = cookie.split('=')[0].trim();
            deleteCookie(cookieName);
            deleteCookie(cookieName, "/");
        });
    }
    //Clear cookies on logout
    window.onload = function () {
        clearAllCookies();
    }
</script>

I pushed this updated code to my test server, and when I clicked my logout button, I navigated to chrome://settings/content/all and saw that the cookie for my website was still there. Is there a more effective way that I can clear the cookies for my web application?



You need to sign in to view this answers

Exit mobile version