12

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.

Community
  • 1
  • 1
vdegenne
  • 12,272
  • 14
  • 80
  • 106

3 Answers3

13

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>
Michael
  • 3,085
  • 1
  • 17
  • 15
  • 1
    You don't need to pollute the scope's public namespace if you don't have to call this function from the view as well. See user4919812's solution. – vsp Feb 22 '16 at 10:10
  • How can you differentiate between the browser closing and a refresh? – Ben Nieting Aug 16 '16 at 20:20
  • @Michael, What if one click directly on close button of Browser tab?? – Hardik Bharadava Oct 20 '16 at 07:17
  • @Michael, Thanks It worked fine for 'window close' , But when I refresh the page then the same function is calling, So is there any other solution? – Vishnu KR Sep 28 '17 at 10:31
7

I think you can use $window to bind the native javascript event on window close e.g.

app.controller('myCtrl', ['$window', '$myService', function ($window, $myService) {
  $window.onbeforeunload = function (evt) {
    $myService.onclose();
  }
}]);
-3

This work?

onbeforeunload, not only is trigger when the window close, also happens when the user refresh the window (ctrl+f5). And if you use $window.onunload, the function never will be executed because the window will be closed before execute the function's code.