Monday, January 15, 2007

Erasing all your cookies

In a previous post I provided some [non-original] code to do basic cookie manipulation in JavaScript. Well, if you're now using cookies to save a whole bunch of user settings and preferences for your web application, you may want to provide an option to let users clear all their saved settings (or perhaps just provide a hidden hot-spot so you can clear your settings for testing purposes which is why I needed this function).

You could keep track of all your cookie names and call the eraseCookie function repeatedly yourself for each cookie. Or, you could name all your cookies with a common prefix for your whole application and use the following function to clear them all out for you.

function eraseCookiesStartingWith(prefix) {
var allCookies = document.cookie.split(';');
for(var i=0;i < allCookies.length;i++) {
var aCookie = allCookies[i];
// remove any whitespace from start of cookie name
while (aCookie.charAt(0)==' ') aCookie = aCookie.substring(1,aCookie.length);
var aCookieName = (aCookie.split('='))[0];
if (aCookie.indexOf(prefix) == 0) {

No comments: