Angular way to delete all cookies when closing the browser

I read other posts discussing ways to clear other browsers from the browser when the browser is closed, but none of them show how to get AngularJS to do this. How to run the cookie removal method in AngularJS to run when the browser closes?

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


ENABLING EFFECTS:


As suggested by @ User2341963, I added a cookie removal code to the run method in the main module of the application. The same exact code works correctly when I put it in the logout() method elsewhere in the application, but when I put breakpoints in the firefox debugger and closed the browser, I see that the cookie removal code never starts when the browser is closed. What specific changes can I make to the code to delete all cookies using AngularJS when the browser is closed?

Here is the code for the main application module, 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'); }; }]); 
+6
source share
1 answer

If you only need cookies because you need to send it to the backend server, you can use the main $ destroy controller.

Using $on.$destroy

This event is called when the controller must be destroyed.

Another option is to use angularjs sessionStorage

Session Storage is deleted when the window closes automatically

+1
source

All Articles