在卸载事件上执行$ http请求

时间:2018-06-28 21:03:14

标签: javascript angularjs ajax

我正在开发一个angular 1.5应用程序,我需要做的一部分工作是检查浏览器是否已关闭/刷新,并向服务器发送请求以执行一些工作。我拥有的代码可以很好地进行刷新,但是在关闭浏览器后无法正常工作。该请求从未根据我在那里运行的日志发送到服务器。我不需要处理任何类型的响应,我只需要确定请求已到达服务器即可。

module.run(['$window', '$rootScope' function($window) {
    $window.onbeforeunload = function() {
  // let everyone know that the window is about to be unloaded. We use this in the AnalystSession service 
  $rootScope.$broadcast('onBeforeUnload');
}
}])


  module.factory("AnalystSession", analystSessionFactory);
  analystSessionFactory.$inject = [
    "$http",
    "$rootScope",
    "$window",
  ];

  function analystSessionFactory($http, $rootScope, $window) {
    var analystSession = {
      analystID: "",
      aSessID: "",
      cSessID: "",
      runningInAnalystContext: false
    };

    /**
     * Uses the $http method to post a cleanup request to a PHP file which will handle the logging off of the analyst session.
     * In the case of an unload event, the graceful method of binding a session and then logging off of that session is too slow to be considered reliable.
     * Here we will send the request to the PHP and trust the PHP to handle the rest. This is much more efficient, but it does not allow us to handle failures
     * in any meaningful way.
     */
    analystSession.__cleanup = function() {
      $http.post('php/analystSessionCleanup.php', {sessid: analystSession.aSessID || store.get('aSessID')});
    }

    // unbind the analyst session when the browser is closed/refreshed
    analystSession.__listener = $rootScope.$on('onBeforeUnload', function() {

      analystSession.__cleanup();
    });

    // probably not neccessary but just to be safe
    $rootScope.$on('$destroy', function () {
      analystSession.__listener();
    })

    return analystSession;
  }

0 个答案:

没有答案