EpokK
EpokK

Reputation: 38092

Detect when user leaves window

I want to detect when user exit window with AngularJS. My app doesn't use ngRoute. So, I can't use $destroy or $locationChangeStart.

Can you help me ?

Upvotes: 2

Views: 1126

Answers (1)

Amir Popovich
Amir Popovich

Reputation: 29836

You can use $locationChangeStart:

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

Or use 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;
}

Upvotes: 3

Related Questions