Problem: On clicking the close button of browser ask for user confirmation with a custom message
Solution: Use the window.onbeforeunload method. This method expects a string value. This string will be displayed to user along with the default string. Default string that is displayed to user is:
Are you sure you want to navigate away from this page?
Press OK to continue, or Cancel to stay on the current page.
You can see an example in action here. Full code is given below.
onbeforeunload event will fire on reloading the page, using browser’s back/forward button or even on clicking an anchor that navigates user from current page to any other location.