I am looking for a possibility to remove all cookies if the user closes the browser window/tag. Is there any chance to trigger a event or anything else?
Asked
Active
Viewed 4,189 times
3
-
what happems with the case when the user may have several tabs of the same website open? why don't do a clean up on the "logout" method? – pedrommuller Sep 19 '14 at 14:03
-
1Why don't you just use session storage? – Cory Silva Sep 19 '14 at 14:43
1 Answers
0
Try this:
function clearCookies(){
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++){
var vals = cookies[i].split("=");
document.cookie = vals[0] + "=;expires=Thu, 21 Sep 1979 00:00:01 UTC;";
}
}
// you will need jquery for this
$(window).on('beforeunload', function () {
clearCookies()
});
or the clear function in angular way:
function clearCookies(){
angular.forEach($cookies, function (value, key) {
$cookieStore.remove(key);
});
}
But if you can use session cookies (without expire value) they will be removed by the browser automatically when the user closes the browser.

Marian Ban
- 8,158
- 1
- 32
- 45
-
2The 'beforeunload' is also fired when the user reload the page. I just want to remove the cookies only if the user close the window or the tab. – Christian Pippert Sep 21 '14 at 14:30