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
I know it's been a while since this question was asked, but I thought I'd contribute my answer as well. The best way I found to reload the page without losing cookies, and remove cookies on window or tab close was to use ng-keydown to watch the F5 Keypress (KeyCode 116).
HTML
CONTROLLER
yourApp.controller('exitController', ['$rootScope', '$scope', '$window', '$cookies', function($rootScope, $scope, $window, $cookies) {
//set refresh to false to start out, it will become true only when we hit the refresh page
$scope.refresh = false;
//This is where we'll actually clear our cookies in the event of a window close
$scope.clearCookies = function() {
$cookies.remove('sessionData');
$cookies.remove('ss-id');
$cookies.remove('ss-pid');
};
//When the user types any key, it will be assessed.
$scope.isRefresh = function(e) {
var keyCode = e.keyCode; //find the key that was just pressed
if(keyCode === 116) { //if the key that was pressed is F5, then we know it was a refresh
$scope.refresh = true;
}
}
//event that handles all refresh requests
window.onbeforeunload = function (e) {
if (!$scope.refresh) { //as long as the trigger for the refresh wasnt initiated by F5, we remove the cookies
$scope.clearCookies();
}
};
}]);