Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to trigger a function on window close using angularjs

I need to execute a function when the user closes the application, but the following points need to be considered :

  • I need to execute a function of one service, then...
  • ... an out-scoped pure-javascript based function is not likely to be useful here
  • As I am using routes, a scoped onLocationChangeSuccess binding is useless as well

therefore this solution is not going to work : https://stackoverflow.com/a/18355715/773595

Because this will be triggered everytime the location change, but what I need is only one trigger when the tab/window is closed.

like image 631
vdegenne Avatar asked May 20 '15 09:05

vdegenne


1 Answers

You can register an onbeforeunload in your controller/directive then you'll have access to the scope. In case of a service i'd register it in the angular.run lifecycle.

angular.module('app', [])
  .controller('exitController', function($scope, $window) {
    $scope.onExit = function() {
      return ('bye bye');
    };

   $window.onbeforeunload =  $scope.onExit;
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="exitController">
  <a href="http://www.disney.com">Leave page</a>
</div>
like image 185
Michael Avatar answered Sep 28 '22 00:09

Michael