Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert user when they hit the browser back button - with good reason

I know this borders on the taboo here, and please don't reply with "you should never do this", etc.

I have a very long form in a wizard, and some users are too used to using the browser's back and forward buttons that they use those instead of the "Back" and "Next" buttons on the form wizard. If they hit the browser's back button, they will lose all of their form data (which is a pain in the ass, since the form is so long).

Is it possible to display an alert that when will have a "take me out of here" button and a "cancel" button, so if they hit cancel it will cancel the function of the back button?

like image 331
Dirty Bird Design Avatar asked Jun 13 '10 20:06

Dirty Bird Design


People also ask

What happens when browser Back button is pressed?

For pages that are set as non-cached, the browser reloads the page from the server when you press Back, as though it was the first time you are visiting it. For cached pages, the browser displays it out of the cache, which is much faster.

How do I get the browser back button event in JQuery?

You can simply fire the “popState” event in JQuery e.g: $(window). on('popstate', function(event) { alert("pop"); });


1 Answers

You should return a message from the onbeforeunload event, like this:

window.onbeforeunload = function() {
    return "Leaving this page will reset the wizard";
};

Note that this event will fire when the user leaves the page for any reason, even after your wizard finishes.
You should set a flag when the wizard finishes and not return a message.

like image 107
SLaks Avatar answered Oct 04 '22 02:10

SLaks