Blog @ ckgagan

Sharing Sharing Sharing.

Ask Confirmtion of User Before Leaving the Page.

Its really annoying when the page redirects to previous page while filling up the form by accident. Specially in chrome when the form field is not in focus and the user hits backspace button, the page gets redirected to previous page. We can stop this by asking the confirmation to user if they wanted to redirect to other page.

First of all we need to determine if we want to show the confirmation or not to the user when they tried to redirect from the page. We can use a variable for this. Lets say it to be

var needToConfirm = false;

and set it to false denoting that we don’t want to show the confirmation.

window.onbeforeunload event gets triggered everytime the page gets reloaded or redirected. We can attach a method to this event handler.

window.onbeforeunload = confirmExit;

Now we need a function that will return the confirmation message when this variable is set to true. The function might look like

function confirmExit()
{
  if (needToConfirm)
  {
    return "{message}";
  }
}

Here message is the string we want to show in confirmation box.

Lets take an example where user is filling up a form. When the form fields are updated, set needToConfirm variable to true. This way when the use tries to navigate away by accident, confirmation dialog will be displayed. But bear in mind, we need to set this variable to false when user clicks the submit button. This way the confirmation dialog will not be displayed while form is submitted.

Comments