My cookie is working fine i m not mentioning date so when the browser window is closed the cookie is deleted.
but when i close a tab in a browser window the cookie is no
The previous answers assume that your cookies are not marked as http-only. If you want to prevent XSS attacks, you should probably set your cookies as http-only, and changing the cookies via javascript will not work.
The solution is to delete the cookie from the server, which will require an HTTP request before the tab is closed.
Most JS libraries will use asynchronous HTTP requests, which will cause the tab to be closed before receiving the expired cookie from the server, so asynchronous calls will not work reliably.
The only way that I was able to make it work reliably (at least on Chrome) was by making a synchronous call:
window.onbeforeunload = function () {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "api/logout", false);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send();
}
Just make sure to keep your Logout endpoint in your server simple so the response is fast and the UI is not blocked for too long.
Edit: as mentioned before, using onbeforeunload to kill the cookies should only be used if it's a single-page application.
You have to delete the cookie on .unload
event
$(window).unload(function() {
$.cookies.del('myCookie');
});
you can call delete cookies function on onunload & onbeforeunload events.
the function to delete cookies is here how to delete cookie in jquery at the time of browser closing?