Tuesday, August 2, 2011

How to delete a cookie written by ASP.NET using client-side JavaScript

What?

Today I spent some time trying to understand why a JavaScript function that I wrote to delete a cookie that was written by ASP.NET was not deleting it properly.

I finally managed to find the reason and thought it might be useful to write about it as it might help someone..



What is so different about it?

Just google / bing for "delete cookie using javascript" and you will see 100s of snippets to delete a cookie using javascript. In order to delete a cookie that was written by ASP.NET, we need to take a slightly different approach.

How?

The cookie string used in JavaScript to delete it must match EXACTLY the cookie string sent by ASP.NET to save it.

ASP.NET sends the following:

cookiename=cookievalue; expires=gmtdate;  path=/

The following JavaScript function successfully deletes a cookie but an ASP.NET cookie wont be deleted using the following:

function DeleteCookie(name){
    var expires = new Date();
    expires.setUTCFullYear(expires.getUTCFullYear() - 1);
    document.cookie = name + '=; expires=' + expires.toUTCString();
}

You have to use something along the lines of the following JavaScript to delete the cookie:

function DeleteCookie(name) {
    var expires = new Date();
    expires.setUTCFullYear(expires.getUTCFullYear() - 1);
    document.cookie = name + '=; expires=' + expires.toUTCString() + '; path=/';
}

Notice that the only difference is "path=/"

It works both on IE and Mozilla!

No comments:

Post a Comment