Javascript 如何使用angularjs在窗口关闭时触发函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30345446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:02:00  来源:igfitidea点击:

how to trigger a function on window close using angularjs

javascriptangularjsevents

提问by vdegenne

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 onLocationChangeSuccessbinding is useless as well
  • 我需要执行一个函数service,然后...
  • ... 超出范围的基于纯 javascript 的函数在这里不太可能有用
  • 当我使用路由时,作用域onLocationChangeSuccess绑定也无用

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

因此这个解决方案是行不通的: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.

因为每次位置更改时都会触发此操作,但我需要的只是在选项卡/窗口关闭时触发一次。

回答by Michael

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.

你可以在你的控制器/指令中注册一个 onbeforeunload 然后你就可以访问范围。如果是服务,我会在 angular.run 生命周期中注册它。

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>

回答by vdegenne

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

我认为您可以使用 $window 在窗口关闭时绑定本机 javascript 事件,例如

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

回答by SilentSei

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.

onbeforeunload,不仅在窗口关闭时触发,在用户刷新窗口时(ctrl+f5)也会触发。如果您使用 $window.onunload,该函数将永远不会被执行,因为该窗口将在执行该函数的代码之前关闭。