Перспектива на примере github сообщения onbeforeunload - PullRequest
0 голосов
/ 07 декабря 2018

Является ли следующий пример из onbeforeunload простым и понятным сообщением?

Может ли оно быть короче или проще?Есть ли более AngularJS способ, чем эти оконные события?

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>

1 Ответ

0 голосов
/ 18 декабря 2018

Проблема связана с безопасностью и не работает с последними версиями Chrome и Firefox.Смотрите это: Crossbrowser onbeforeunload? и это: jQuery beforeunload настраиваемое всплывающее окно для выхода со страницы

<!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>
...