Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS way to remove all cookies when browser is closed

I have read other postings that discuss ways that other technologies clean up the browser cookies when the browser is closed down, but none of them show how to get AngularJS to do this. How do I trigger a cookie removal method in AngularJS to run when the browser is closed?

In AngularJS 1.4.8, cookies can be removed with the syntax $cookies.remove('keyname'). I can write a method to remove all the cookies by name. But how do I make sure that the cookie removal method is called whenever the browser is closed? Is the syntax any different if I want the method to be called when a browser tab is closed?


ONGOING EFFORTS:


As per @User2341963's suggestion, I added cookie removal code to the run method in the main module of the app. The same exact code runs correctly when I put it in a logout() method elsewhere in the app, but when I put breakpoints in the firefox debugger and close the browser, I see that the cookie removal code is never run when the browser is closed. What specific changes do I make to the code to get the cookies to all be removed by AngularJS when the browser is closed?

Here is the code for the main module of the app, including the run() method:

angular
    .module('hello', [ 'ngRoute', 'auth', 'home', 'secure', 'public1', 'navigation' ])
    .config(

            function($routeProvider, $httpProvider, $locationProvider) {

                $locationProvider.html5Mode(true);

                $routeProvider
                .when('/', {
                    templateUrl : 'js/home/home.html',
                    controller : 'home'
                })//plus other routes
                .otherwise('/');

                $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

            }
    ).run(['$cookies', '$window', '$log', function($cookies, auth, $window, $log) {

        //other stuff

        $window.onbeforeunload = function() {
            // Clearing all cookies now!
            $cookies.remove("AUTH1"); 
            $cookies.remove("AUTH2");
            $cookies.remove('procStep');
            $cookies.remove('usrname');
            $cookies.remove('exists');
            $cookies.remove('wid');
        };
    }]);
like image 511
CodeMed Avatar asked Feb 10 '16 01:02

CodeMed


1 Answers

If you need only cookies, because you need it to be sent to backend server, you can use the main controller's $destroy event.

Using $on.$destroy

This event called when the controller about to be destroyed.

Other option is to use angularjs sessionStorage

Session Storage removed when the window is closed automatically

like image 134
Itamar Avatar answered Sep 22 '22 14:09

Itamar