If user tries to leave unsaved edited form, a message box pop-up
"This page is asking you to confirm that you want to leave - data you have entered may not be saved. Leave Page and Stay on Page"
Can we invoke this confirmation box through some special function of browser? I want to implement it in AngularJS application
How to warn user before leaving page JavaScript? To make a warning alert or confirm dialog display when the user reloads the page or closes a tab using javascript, we can use window. addEventListener() and beforeunload events like the script above.
How to display warning before leaving the web page with unsaved changes using JavaScript ? The onbeforeunload event handler is used for processing beforeunload events. This event is fired whenever a window is about to unload its resources.
The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.
The onbeforeunload event fires when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.
Warlock's answer is partly right, but in doing so, you'd break testability.
In Angular, you'd want to use $window, and you'll want to watch $dirty
on your form. You'll need to have a named form, notice name="myForm"
below. Then you can $watch
$dirty
on the form in your $scope
:
app.controller('MainCtrl', function($scope, $window) {
$scope.name = 'World';
var win = $window;
$scope.$watch('myForm.$dirty', function(value) {
if(value) {
win.onbeforeunload = function(){
return 'Your message here';
};
}
});
});
HTML
<form name="myForm">
Name: <input type="text" ng-model="name"/>
</form>
Here's a plunk to demonstrate: http://plnkr.co/edit/3NHpU1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With