在你的模块中run
函数,你必须声明beforeunload
事件是这样的:
.run(['$window', 'Utilities', function($window, Utilities) {
$window.addEventListener('beforeunload', function(e)
// Place code here
};
});
不是这样:
.run(['$window', 'Utilities', function($window, Utilities) {
window.onbeforeunload = function() {
// Place code here
};
}]);
这是一个要使用的片段onbeforeunload
与 Angular 的事件。
Note:根据您的浏览器,点击后代码片段将不起作用保存项目按钮,然后您尝试关闭此窗口。然后,您需要将代码粘贴到您自己的项目中。
附加信息
最近的 HTML 规范现在禁止自定义弹出消息,而是显示通用消息。
因此,始终可以阻止导航,但无法再指定自定义消息
这始终适用于 IE11,但不会持续很长时间(直到下一次更新)。
关于此的 HTML 规范:https://html.spec.whatwg.org/multipage/browsers.html#unloading-documents https://html.spec.whatwg.org/multipage/browsers.html#unloading-documents
关于此的 Chrome/Safari 文档:https://www.chromestatus.com/feature/5349061406228480 https://www.chromestatus.com/feature/5349061406228480
angular.module('app', []);
angular
.module('app')
.controller('ExampleController', ['$scope', 'Utilities', 'ItemService', function($scope, Utilities, ItemService) {
// Expose Utilities to make pending state available in template
$scope.Utilities = Utilities;
// Use item service to save our item
$scope.save = function() {
ItemService.saveItem();
}
$scope.fireCloseEvent = function() {
$scope.$emit('close');
}
$scope.$on('close', function(event) {
Utilities.toggleSavePending();
});
}])
.factory('ItemService', ['Utilities', function(Utilities) {
return {
saveItem: function() {
// ...
// Toggle global save pending state
Utilities.toggleSavePending();
}
}
}])
.factory('Utilities', function() {
var savePending = false;
return {
toggleSavePending: function() {
savePending = !savePending;
},
isSavePending: function() {
return savePending;
}
}
})
.run(['$window', 'Utilities', function($window, Utilities) {
$window.addEventListener('beforeunload', function(e) {
// If save pending state is truthy, prevent browser window from closing
if (Utilities.isSavePending()) {
var message = 'Warning! Save pending...';
e = e || window.event;
if (e) {
e.returnValue = message;
}
return message;
}
});
}]);
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ExampleController">
<button ng-click="save()" ng-disabled="Utilities.isSavePending()">Save item</button>
<button ng-click="fireCloseEvent()">Fire Close Event</button>
<div ng-if="Utilities.isSavePending()">A message should be displayed when you close the window</div>
</body>
</html>