Originally posted on my notebook: https://mashiro.top/2018/05/11/add-a-version-control-for-cookies/


When adding some new features to my JavaScript, I find the remaining cookies are pretty hard to deal with that some of them were set by actions such as click and hover. So firstly I considered doing something to clean all cookie at once:

if (getCookie("cookie_control")!="2018/5/11") {
    deleteAllCookies();
    setCookie("cookie_control","2018/5/11",365);
}

But I found there is no such an easy deleteAllCookies() method!

As this answer said:

There is no 100% solution to delete browser cookies.

The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

So my idea is to add a Cookie version control with a full set of setting, getting and removing of cookies:

var cookie_version_control = '---2018/5/11';

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name+cookie_version_control + "=" + (value || "")  + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name+cookie_version_control + "=";
    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 removeCookie(name) {   
    document.cookie = name+cookie_version_control+'=; Max-Age=-99999999;';  
}

Now everytime you want to update your cookies, it's OK just modifying the content of cookie_version_control.

Q.E.D.

Comments