How can I handle browser tab close event in Angular? Only close, not refresh

后端 未结 5 1964
时光取名叫无心
时光取名叫无心 2020-11-30 09:52

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

5条回答
  •  一向
    一向 (楼主)
    2020-11-30 10:16

    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();
        }
    };
    

    }]);

提交回复
热议问题