How to call an Angular method when browser closes

583 Views Asked by At

I'm relatively new in AngularJS and I have been asked to modify our application so that when the user closes the browser, we also log them out of Auth0 service.

I have the code below but I can't get it to fire. Kindly help.

$rootScope.$on("$destroy", function() {
    lockService.logout();
});

lockService.logout() holds the functionality that successfully logs out the user when they click logout button, including the Auth0 signout function.

Somewhere I read that I can use the $on.$destroy of the main Controller but I am not sure how to do this. The above code is in fact inside the mainController function but it still doesn't work.

This is where I found my answer: https://stackoverflow.com/a/36444134/1168597

2

There are 2 best solutions below

0
On BEST ANSWER

I have found a much cleaner and more effective approach.

$rootScope.$on('$locationChangeStart', function () {

    if (!($window.performance.navigation.type === 1) && lockService.isAuthenticated()) {
        $rootScope.logout();
    }

});

So here if window.performance.navigation.type is 1, it means the page was refresh-ed. What I do then is if it is not refreshed AND my lockService.isAuthenticated() returns true, I logout the user.

1
On

You can add a directive like this to your body element.

<body body-unload></body>

app.directive('bodyUnload', [
    function () {
        return {
            restrict: 'A',
            replace: false,
            link: function (scope, element) {
                function cleanupApp(){
                 // do cleanup here
                }
                element[0].onbeforeunload = function() {
                        cleanupApp();
                };
            }
        };
    }
]);