1

I am trying to implement some code to prevent the back button from doing anything on a page in my site. Page posts a form to process a payment, so don't want the user to press back otherwise it ends up in a weird user experience. There is serverside code to handle it, but would like to prevent it clientside as much as possible.

My issue is that even if I use methods like the ones mentioned here: how to stop browser back button using javascript

The problem is that although the page never goes back now, as soon as the back button is pushed the form POST gets canceled.(Using Chrome browser.)

Code I have currently is:

    function() {
        if(window.history && window.history.pushState) {
            window.history.pushState({ page: 1 }, $(document).find("title").text(), null);
            window.addEventListener('popstate', function (e) {
                e.preventDefault();
                e.stopPropagation();
                window.history.pushState({ page: 1 }, $(document).find("title").text(), null);
            });
        }
        else {
            window.location.hash = "pp";
            window.onhashchange = function (e) {
                e.preventDefault();
                e.stopPropagation();
                window.location.hash = "pp";
            };
        }
    }

Is there actually anything I can do here?

Community
  • 1
  • 1
David Esteves
  • 1,614
  • 2
  • 15
  • 22
  • The best method is to just use the [Post/Redirect/Get](https://en.wikipedia.org/wiki/Post/Redirect/Get) pattern and be done with it. – Brad C Jul 02 '15 at 13:44

1 Answers1

0

Unfortunately there's not a lot you can do. You can stop the end result of pressing the back button (changing the page), but you can't stop the side effects of clicking it (causing currently pending requests to halt).

The best you can do is capture when the back button is pressed, determine if the form was sent but no response was received, and then alert the user that the form was likely sent. Then you could attempt to direct the user to next page, which you could design to kick back to the payment page if none was received.

It's problems like this that are hard to analyze for edge cases. :)

cyberbit
  • 1,345
  • 15
  • 22