Question

I know this question has been asked a thousand times but none of the answers really give me what I'm looking for. I am using jQuery cookie to store some information, but I want them to expire when the browser closes. window.unload is not a viable option (read: doesn't work.)

My question is this: is it actually possible to have the cookies set to expire when the browser closes, like a session? If so, does anyone know how?

Update: Turns out it's quite simple, instead of passing expiry: 0 (which didn't work), just don't pass any expiry at all. Well, this explains why there wasn't many questions.

Thanks all.

Was it helpful?

Solution

Turns out it's quite simple, instead of passing expiry: 0 (which didn't work), just don't pass any expiry at all. Well, this explains why there wasn't many questions.

So instead of passing expiry with the flags like so:

$.cookie(key, value, { expiry: 0, domain: '', path: '' });

You just omit the expiry value:

$.cookie(key, value, { domain: '', path: '' });

And it works. It's such a simple thing, that it confused me.

But thanks anyway!

OTHER TIPS

It's possible in the RFC 2965 specification. That said it would be possible if you set the "Discard" property in your cookie handling code and if the browser supports it.

That said: jQuery cookie doesn't support the Discard-property. You would have to extend the jQuery-Cookie code like so (it's about line 57 in the original file):

        return (document.cookie = [
            config.raw ? key : encodeURIComponent(key),
            '=',
            config.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path    ? '; path=' + options.path : '',
            options.domain  ? '; domain=' + options.domain : '',
                            options.discard ? '; Discard=' + options.discard : '',
            options.secure  ? '; secure' : ''
        ].join(''));

if you use a default setup like this

 $.cookie.defaults = { path: '/', expires: 365 };

then you need to use the following attribute for each cookie value

$.cookie(key, value, { expires: null });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top