1

Is the following example of onbeforeunload message straightforward as it gets?

Can it be shorter or easier? Is there a more AngularJS way vs having those window events?

angular.module('TestApp', [])
.factory('beforeUnload', function ($rootScope, $window) {
    // Events are broadcast outside the Scope Lifecycle

    $window.onbeforeunload = function (e) {
        var confirmation = {};
        var event = $rootScope.$broadcast('onBeforeUnload', confirmation);
        if (event.defaultPrevented) {
            return confirmation.message;
        }
    };

    $window.onunload = function () {
        $rootScope.$broadcast('onUnload');
    };
    return {};
})
.run(function (beforeUnload) {
    // Must invoke the service at least once
});
function TestController($scope) {
    $scope.$on('onBeforeUnload', function (e, confirmation) {
        confirmation.message = "All data willl be lost.";
        e.preventDefault();
    });
    $scope.$on('onUnload', function (e) {
        console.log('leaving page'); // Use 'Preserve Log' option in Console
    });
}
<!DOCTYPE html>
<html data-ng-app="TestApp">
<head>
<script src="http://code.angularjs.org/1.2.9/angular.js"></script>
</head>
<body data-ng-controller="TestController">
This is a test
<a href="http://www.google.com/">Google</a>
</body>
</html>
Stanislav Kvitash
  • 4,614
  • 18
  • 29
Rod
  • 14,529
  • 31
  • 118
  • 230
  • could use event `$locationChangeStart`. RE https://coderwall.com/p/nnse0g/confirmation-on-leaving-the-current-page-in-an-angular-js-app – Luke Hutton Dec 17 '18 at 18:34

1 Answers1

0

The problem is related to the security and it does not work with the latest version of chrome and firefox. See this:Crossbrowser onbeforeunload? and this:jQuery beforeunload custom pop up window for leaving a page

<!DOCTYPE html>
<html>
<body onbeforeunload="return myFunction()">

<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>

<a href="https://en.wikipedia.org">Click here to go to wikipedia.org</a>
    
<script>
function myFunction() {
  return "Write something clever here...";
}
</script>

</body>
</html>
I_Al-thamary
  • 3,385
  • 2
  • 24
  • 37