Delete cookie by name?
In order to delete a cookie set the expires
date to something in the past. A function that does this would be.
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
Then to delete a cookie named roundcube_sessauth
just do.
delete_cookie('roundcube_sessauth');
You should define the path on which the cookie exists to ensure that you are deleting the correct cookie.
function set_cookie(name, value) {
document.cookie = name +'='+ value +'; Path=/;';
}
function delete_cookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
If you don't specify the path, the browser will set a cookie relative to the page you are currently on, so if you delete the cookie while on a different page, the other cookie continues its existence.
Edit based on @Evan Morrison's comment.
Be aware that in some cases to identify the correct cookie, the Domain
parameter is required.
Usually it's defined as Domain=.yourdomain.example
.
Placing a dot in front of your domain name means that this cookie may exist on any sub-domain (www
also counts as sub-domain).
Also, as mentioned in @RobertT's answer, HttpOnly
cookies cannot be deleted with JavaScript on the client side.
//if passed exMins=0 it will delete as soon as it creates it.
function setCookie(cname, cvalue, exMins) {
var d = new Date();
d.setTime(d.getTime() + (exMins*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
setCookie('cookieNameToDelete','',0) // this will delete the cookie.