59
votes

How to dynamically, via javascript, delete a session cookie, without manually restarting the browser?

I read somewhere that session cookie is retained in browser memory and will be removed when the browser is closed.

// sessionFooCookie is session cookie
// this code does not delete the cookie while the browser is still on
jQuery.cookie('sessionFooCookie', null);

Thanks.

More Info: The code snippet above is a javascript code snippet, using jQuery and its jQuery.cookie plugin.

7

7 Answers

91
votes

A session cookie is just a normal cookie without an expiration date. Those are handled by the browser to be valid until the window is closed or program is quit.

But if the cookie is a httpOnly cookie (a cookie with the httpOnly parameter set), you cannot read, change or delete it from outside of HTTP (meaning it must be changed on the server).

34
votes

Be sure to supply the exact same path as when you set it, i.e.

Setting:

$.cookie('foo','bar', {path: '/'});

Removing:

$.cookie('foo', null, {path: '/'});

Note that

$.cookie('foo', null); 

will NOT work, since it is actually not the same cookie.

Hope that helps. The same goes for the other options in the hash

6
votes

There are known issues with IE and Opera not removing session cookies when setting the expire date to the past (which is what the jQuery cookie plugin does)

This works fine in Safari and Mozilla/FireFox.

2
votes

This needs to be done on the server-side, where the cookie was issued.

2
votes

you can do this by setting the date of expiry to yesterday.

My new set of posts about cookies in JavaScript could help you.

http://www.markusnordhaus.de/2012/01/20/using-cookies-in-javascript-part-1/

0
votes

If it is a session cookie + hostOnly cookie (like default tapestry session's cookies) To delete from Javascript you also must not specify domain when editing/expire cookie, and not specify expire date and set value to null.

function clearHOnlySessionCookie(name,  path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=null; path=" + path+";";
};
-3
votes

Deleting a jQuery cookie:

$(function() {
    var COOKIE_NAME = 'test_cookie';
    var options = { path: '/', expires: 10 };
    $.cookie(COOKIE_NAME, 'test', options); // sets the cookie
    console.log( $.cookie( COOKIE_NAME)); // check the value // returns test
    $.cookie(COOKIE_NAME, null, options);   // deletes the cookie
    console.log( $.cookie( COOKIE_NAME)); // check the value // returns null
});