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:
The following JavaScript function successfully deletes a cookie but an ASP.NET cookie wont be deleted using the following:
You have to use something along the lines of the following JavaScript to delete the cookie:
Notice that the only difference is "path=/"
It works both on IE and Mozilla!
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