When does JavaScript session expire? How to delete cookie on session end?

4.5k Views Asked by At

I would like to delete the cookie named "username" once the user closes their tab/browser. I am using the following code to detect if user closes and cookie should be deleted. But cookie is still there. Why?

In browser console resources, it shows cookie expiry field as "session". When does a session end?

// delete cookies when user closes browser/tab
$(window).unload(function() {
   $.removeCookie('username', { path: '/' });
});
1

There are 1 best solutions below

0
On

To create cookie the js is:

$.cookie('username', 'your value');

To remove the same cookie the code is:

$.removeCookie('username', '', { path: '/'});

You missed the second parameter, the value, so in this case your cookie will expire at session end.

The library I used is:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>

This library is no more maintained. With the new plugin:

<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.1.0/js.cookie.min.js"></script>

To create a cookie:

Cookies.set('username', 'value');

and to remove:

Cookies.remove('username');

By default, if no expire date is specified, the Cookie is removed when the user closes the browser (session cookie).

Because a browser can be closed with alf+f4 or with the X or with a kill signal you can only handle and rely on the cookie expire time.