重新加载前的窗口确认消息



我的代码工作正常,但我只是想知道这是否正常。我在 Linux 中尝试了我的代码,并且可以更改退出页面或重新加载之前的确认消息。但是,当我在Mac上尝试时,我看到的唯一消息是"您所做的更改可能无法保存"。是因为代码还是因为操作系统,消息的行为是这样的。它发生在火狐浏览器的铬中

代码为:

<!DOCTYPE html>
<html data-ng-app="TestApp">
<head>
<script src="http://code.angularjs.org/1.2.9/angular.js"></script>
<script>
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
    });
}
</script>
</head>
<body data-ng-controller="TestController">
This is a test
<a href="http://www.google.com/">Google</a>
</body>
</html>

附言

上面的代码是AngularJS,但即使是使用纯javascript的相同功能也以相同的方式运行。

代码很好。

参考资料指出

在 Firefox 4 及更高版本中,返回的字符串不会向用户显示。相反,Firefox 显示字符串"此页面要求您确认是否要离开 - 您输入的数据可能无法保存。

它还指出Chrome 51.0和Firefox 44.0中的"自定义文本支持已删除"。

最新更新