Search code examples
javascriptjquerybrowserbrowser-history

Is there a way to bind a handler to browser history back button?


For example the user came to the page from example.com/home.html to the page example.com/checkout.html. I wonder if there is a way to assign a history back to something like example.com/new_offers.html?

So, when clicking his browser back button, instead of going to home.html the user will be redirected to new_offers.html

I know it may sound awkward, but it's just the example and the thing I need this for is a bit different. Also, I need to do this using JavaScript only (nothing server-side).

UPD: I figured out that it'd be clearer to ask whether it's possible to bind a handler to browser back button like (jQuery):

$(browser.backButton).click(function(e){ ... })


Solution

  • Instead of going to the checkout page from the home page, you can go to new_offers, which checks a variable checked_out. If checked_out is false, then redirect the user to checkout passing along all the form information. If checked_out was true, then display the new_offers page. checked_out will be set to true at the checkout page.

    In this way, if the user clicks back at the checkout page, the user will actually go to the new_offers page.

    I don't like this design very much as it means that a user has to click back twice quickly to get to a previous website, but it does satisfy your goals.

    In other words, your current design does this:

    home --> checkout

    Instead, do this:

    home --> new_offers -- (redirect) --> checkout

    So that new_offers redirects to checkout immediately unless it sees that the user has already checked out.