내 코드가 정상적으로 작동하는지 궁금하다. 리눅스에서 코드를 시험해 보았고 페이지를 종료하거나 다시로드하기 전에 확인 메시지를 변경했다. 그러나 Mac에서 시도했을 때 내가 본 유일한 메시지는 "변경 한 내용을 저장하지 못할 수도 있습니다"입니다. 그것은 코드 때문이거나 OS가 메시지가 그와 같이 행동하기 때문입니다. 파이어 폭스다시로드하기 전에 메시지 확인 메시지
의 크롬에 코드인지 여부를 발생
<!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와하지만, 순수 자바 스크립트의 사용과도 같은 기능이 동일한 방식으로 동작합니다.
그래서 대답하겠습니다. 정말 고맙습니다! –
시스템을 다시로드 할 때 또 다른 문제가 있습니다. 'onUnload'는 아무 것도하지 않습니다. 경고를 시도했지만 아무 일도 없었습니다 –
@estus 브라우저를 닫을 때 사용자에게 사용자 지정 메시지를 표시 할 수있는 방법이 있습니까? –