Codemonkey
Codemonkey

Reputation: 4809

Failing to delete a cookie using JavaScript - what am I doing wrong?

I'm trying to delete a cookie in Android Chrome (latest version).

DevTools (phone connected to PC via USB) shows the following cookies when I navigate my phone to www.domain.com/admin/clearcookies:

Name                Value     Domain           Path    Expires
data-cookie-name    foo       www.domain.com   /       2020-09-16T07:57:01.000Z
data-cookie-name    bar       .domain.com      /       2021-03-24T09:03:04.000Z

On page load I run the following javascript:

function deleteOldWwwScopedCookiesThatWereConflictingWithNewNonWwwCookiesThatISwitchedToBecauseOfLanguageSubdomains()
{
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        var tmp = name + "=;domain=www.domain.com;expires=Thu, 01 Jan 1970 00:00:00 GMT";

        console.log(tmp);
        document.cookie = tmp;
    }
}

deleteOldWwwScopedCookiesThatWereConflictingWithNewNonWwwCookiesThatISwitchedToBecauseOfLanguageSubdomains();

I reload the page nummerous times, and see the console correctly output

data-cookie-name=;domain=www.domain.com;expires=Thu, 01 Jan 1970 00:00:00 GMT

There's no errors in the console.

But if I view the page request in the network tab I get the same cookies listed as above.

I've tried a couple of variations as well:

No dice.

Nothing I seem to try will get rid of this unwanted cookie that is overriding the .domain.com one.

What am I doing wrong? Please!

Upvotes: 0

Views: 40

Answers (1)

Codemonkey
Codemonkey

Reputation: 4809

I think what I needed was a combination of the two alternatives that I'd tried.

Adding a path AND dropping the domain:

data-cookie-name=;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT

I've no idea why it's important to NOT specify the domain. Can anyone explain?

Upvotes: 0

Related Questions