I've got a cookie being set in a framework I'm developing within via JavaScript (the framework appears to be using https://github.com/carhartl/jquery-cookie). I'm developing within this framework but don't have access to the framework code and I want to delete a cookie via JavaScript (I do not have access to anything serverside within this framework).
Inspecting the cookie via Chrome, I can tell a lot about it:
"domain": "www.example.com",
"expirationDate": 1667235180,
"hostOnly": true,
"httpOnly": false,
"name": "my_cookie",
"path": "/",
"secure": false,
"session": false,
"storeId": "0",
"value": "123456789"
It is hostOnly, but that should be fine as I am trying to remove from the same domain set in the domain field.
I'm trying to remove it using the following code:
function clearCookie(name, domain, path) {
var domain = domain || document.domain;
var path = path || "/";
document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};
clearCookie('my_cookie', 'www.example.com', '/');
When I do this however, it creates a new session cookie with a domain of ".www.example.com" (note the extra period) and doesn't delete the current cookie.
What am I missing?
Old question, but I just ran into this and discovered the issue.
If you have a hostOnly cookie, do not specify the domain when you modify/expire it.
Most cookie handling libraries will auto-specify the domain if one is not provided, making it difficult, if not impossible, to edit a hostOnly cookie.
You can't actually delete a cookie via javascript. What you do is set the existing cookie to expire and then allow the browser to handle its destruction. If you check the jquery-cookie source you can see that it actually has a function to destroy cookies that you could use here to simplify things.
The simple answer here is to use the existing frameworks remove function.
I think there's a problem with how you're setting the expiration. Setting cookies with JavaScript requires a UTC/GMT format for the date. See this related answer:
Which date formats can I use when specifying the expiry date when setting a cookie?