Skip to content

Instantly share code, notes, and snippets.

@schmuli
Last active March 19, 2021 18:25
Show Gist options
  • Save schmuli/8781415 to your computer and use it in GitHub Desktop.
Save schmuli/8781415 to your computer and use it in GitHub Desktop.
A simple AngularJS service for handling the 'onbeforeunload' event
<!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>
@StefanoSega
Copy link

It doesn't work consistently in all IE versions and on Chrome when closing the tab, I think is an issue with the event itself, but it works fine in all browsers if used as an attribute of the "body" DOM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment