检测用户何时离开窗口

时间:2014-05-07 05:27:52

标签: angularjs

我想用AngularJS检测用户退出窗口的时间。我的应用不使用ngRoute。因此,我无法使用$destroy$locationChangeStart

你能帮助我吗?

1 个答案:

答案 0 :(得分:3)

您可以使用$locationChangeStart

$scope.$on('$locationChangeStart', function( event ) {
    var answer = confirm("Are you sure you want to leave this page?")
    if (!answer) {
        event.preventDefault();
    }
});

或使用onbeforeunload

window.onbeforeunload = function (event) {
  var message = 'Are you sure you want to leave this page?';
  if (typeof event == 'undefined') {
    event = window.event;
  }
  if (event) {
    event.returnValue = message;
  }
  return message;
}