Handling the Browser Back Button with JavaScript Confirm Box

Posted on Jan 15, 2023

You can use the window.onbeforeunload event to handle the browser back button event. This event is triggered when the user is about to leave the page, whether by clicking on a link, submitting a form, or using the browser's back or forward buttons.


Here's an example of how you can use this event to display a confirm box and handle the user's response:

window.onbeforeunload = function(event) {
  event.preventDefault();
  event.returnValue = '';
  return '';
};


The returnValue property is used to set the message that will be displayed in the confirm box.

window.onbeforeunload = function(event) {
  const confirmationMessage = 'Are you sure you want to leave?';
  event.returnValue = confirmationMessage;
  return confirmationMessage;
};


You can then use the confirm() function to display a confirm box, and use the result to decide whether to allow the back button action or not.

window.onbeforeunload = function(event) {
    const confirmationMessage = 'Are you sure you want to leave?';
    if(!confirm(confirmationMessage)){
        event.preventDefault();
    }
};


Please note that some modern browsers will prevent the prompt to show, to handle this you may use the beforeunload event instead of onbeforeunload, however, some browsers may not support it.

Leave a comment:

Thank you for your comment. After a while, our moderators will add it.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

© Twiwoo 2023 Cookie Policy