Title: Display a customized confirm box in angularjs when user leaves a page
Tags: javascript;angularjs;angularjs-material
Question: My requirement is to display a customized confirm box when the user leaves a page without saving form data.

I used the ```window.onbeforeunload``` event it is displaying google chrome related predefined confirm box. When the user changes any form and trying to reload, tab close or route change I want to display a $mdDialog.confirm and asking user to leave the page or stay on the same page. How do I make one?

Comment: I don't think that's possible and that's by design. The only notification you can give is using the browser's own dialog. This is so pages can't hijack users indefinitely.


Here is another answer: For security reasons, this cannot be done. You can find more details in the MDN page on the beforeunload event.

In the past, you could return a custom string that was displayed to the user, but these days even that is ignore. The best you can do is instruct the page to show the standard dialog that you already have. (And in some browsers and some scenarios, even that instruction may be ignored.)

An alternative is to include a button in the page for leaving the form. Although that still does not prevent users from navigating away from the page directly, if it is sufficiently visible, in many cases users are more likely to click that than navigating directly. It also serves as a passive reminder that the form needs explicit saving or cancelling (depending on your specific details, of course).


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:10/14/17', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><angularjs><angularjs-material>', 'Title': 'Display a customized confirm box in angularjs when user leaves a page', 'ViewCount': 281, 'id': 46741323, 'user_AboutMe': '<p>Learn Java programming with complete source code examples and also provide android, javascript, jquery and ajax tutorials and examples.</p>\n', 'user_AccountId': 6420590.0, 'user_DisplayName': 'Java4you', 'user_Reputation': 486.0, 'user_Views': 81.0, 'user_id': 4977424.0}}