angularjsangularjs-scopesession-cookiesangularjs-rootscopeauth0-lock

How to call an Angular method when browser closes


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


Solution

  • 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.