My goal is remove user cookies when browser tab closed.
Is it possible? Can I handle browser tab close event without refresh case?
If I use beforeunlo
$window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
console.log("closing the tab so do your small interval actions here like cookie removal etc but you cannot stop customer from closing");
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
This is quite debated on whether we can do it or not in a fool proof manner. But technically not a lot of things can be done here since the time you have is quite less and if customer closes it before your actions complete you are in trouble, and you are at mercy of the client completely. Dont forget to inject $window. I advice not to depend on it.
javascript detect browser close tab/close browser
Update:
I was researching this issue along with some recommendations. And apart from this above option, the best way you can handle such cases is by creating sessions with no activity timeout of may be 25-30 mins. Convert all your cookies that need to be destroyed into sessions with timeout. Alternately, you can set cookie expiry but then the cookie stays in the browser until next login. Less than 25-30 mins of session inactivity is not completely dependable since you can get logged out if the client is not using the browser for 10-15 mins. I even tried the capturing events from link (<a>) or (<submit>) or (keypress) based events. The problem is it handles page refresh well. But it does not remove the problem of client closing the browser or browser tab before your cookies are deleted. It is something you have to consider in your use case and forcefully trade off due to no control on it. Better to change the design on its dependence to a better architecture than to face mentioned problems later.