Search code examples
javascriptjqueryhtmlbrowser-history

Is there an event for the browser's back button being pressed?


I am supporting an e-commerce app, which pretty much makes and submits orders.

A user found that if they submit their order, and press back really quickly, they can cause an error condition.

I want to prevent this. When the user clicks submit, I want to bind some kind of event to the browser's back button that instead will redirect them to the Index page. However, after about two hours of Googling (including a few StackOverflow topics), I have not found any clear way of influencing the behavior of the back button.

I briefly attempted to use history.pushState(), but as the HTML 5 documentation mentions, that will not cause a redirect; it merely alters the displayed URL/state.

Similarly, the history.onpopstate event appears unhelpful, because it occurs whenever a state is removed from the history listing; I'm looking for an event that occurs whenever the history listing is traversed backwards.

Question: Does an event for the browser's back button, or at least a way to prevent this particular stupid user trick exist?


Solution

  • You can't listen to the browser back button because it's outside of your reach (it's not part of the DOM).

    What you can do is fix the previous page so that it detects if you've used the back button.

    Without more information I can't give you any tips on how to achieve that.

    Also, an error condition is not necessarily a bad thing. Just make sure it's clear what is happening: the error message should make sense.