重新加载之前的窗口确认信息
问题描述:
我的代码工作正常,但我只是想知道这是否正常..我在Linux和我的确认消息中尝试我的代码,然后退出页面或重新加载可以更改。但是,当我在Mac上试用时,我看到的唯一消息是“您所做的更改可能无法保存”。是因为代码还是因为操作系统,消息的行为如此。它发生是否在Firefox重新加载之前的窗口确认信息
的铬的代码是:
<!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>
PS
上面的代码是AngularJS但即使使用纯JavaScript的相同的功能的行为方式相同。
答
代码很好。
在Firefox 4及更高版本返回的字符串不会显示给用户。相反,Firefox会显示字符串“此页面要求您确认您要离开 - 您输入的数据可能无法保存。”
它还指出在Chrome 51.0和Firefox 44.0中“自定义文本支持已移除”。
这就是答案。非常感谢! –
我重新加载系统时出现另一个问题。 'onUnload'不起任何作用。我试过警告但没有任何反应 –
@estus有没有办法在用户关闭浏览器时向用户显示自定义消息? –