Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help required on onbeforeunload or click on browser back button

If a user clicks the browser's back button, then I want a prompt to appear and ask for confirmation. If the user clicks 'OK', then it should navigate to xx.html. If the user clicks 'Cancel', then it should prevent the navigation. How can I do this?

Note: Already I tried the onbeforeunload method, but it is working for all the navigation actions. For Example, clicking the link on the page will also fire this event and show the message to the user.

like image 632
Bala Duraimanickam Avatar asked Oct 22 '25 19:10

Bala Duraimanickam


2 Answers

You can't. The best you can do is use onbeforeunload and remove that event when clicking on a normal link:

<script type="text/javascript">
window.onbeforeunload = function() {return "Are you sure?"}
</script>

<a href="somewhere.html" onclick="window.onbeforeunload = null;">Leave</a>
like image 91
RoToRa Avatar answered Oct 24 '25 09:10

RoToRa


There's no way to differentiate between navigational actions in the onbeforeunload event. You could disable it for all links/forms on the page by removing the window.onbeforeunload handler in each link's onclick handler, or onsubmit for forms. However, you will still be unable to tell whether the user clicked back, forward, a bookmark, etc or typed a new address into the address bar.

like image 42
Andy E Avatar answered Oct 24 '25 09:10

Andy E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!