Possible Duplicate:
Is there a way to catch the back button event in javascript?
In my application I want only a certain number of scripts (Text1.php, Text2.php and Text3.php) to contain a piece of code where that if the user clicks on the back browser button, it will display a confirmation box like the one below:
confirm("You have clicked on the browser's back button. If you confirm to go back via the browser back button, you will be logged out and lose your current assessment details." + "\n" + "\n" + "Are you sure you want to go back and lose current assessment details?" + "\n" );
The requirments are the following:
- How to show the confirm if the user clicks on the back browser button?
- If user confirms the confirmation then navigate to Text4.php (This is where it logs out user)
- If user cancels confirmation then just close confirmation box so user can continue what they are doing (guessing this is something to do with
return false; - Only want this to happen for scripts (Text1.php, Text2.php and Text3.php)
- Need it to work on all major browsers (IE, Chrome, Firefox, Safari, Opera)
Thank you
Note: You should ONLY do this if you NEED to prevent the person from leaving (that is, if they’ve inputted some important data and will lose it by navigating away). Also note that you cannot customize the confirmation popup in more recent browsers. (Older browsers allowed customizing the confirmation message body.) These are the restrictions of such a feature.
You can use the
beforeunloadevent to achieve this. In older browsers, you could return a custom string for the confirmation prompt:However, as mentioned by @formicini in the comments, more recent browsers (Chrome 87, for example) do not allow a custom string. Returning any non-
undefinedvalue will show the confirmation prompt, but will just display the browser’s generic message—even if it’s a string.I would also suggest you unbind this upon someone leaving the page in the desired way (a cancel button?), or you may run into undesirable behavior.
For example: