0

I want to redirect client to custom controller when he click back browser button.

Do you know any clear ways to catch back button event and force to call server?

Bests, Thank you

Liam
  • 27,717
  • 28
  • 128
  • 190
  • 2
    Possible duplicate of [Intercepting call to the back button in my AJAX application: I don't want it to do anything!](http://stackoverflow.com/questions/1844491/intercepting-call-to-the-back-button-in-my-ajax-application-i-dont-want-it-to) – Liam Oct 24 '16 at 09:44

1 Answers1

0

Back button question is quite well answered on SO. A quick search will turn up lots of extra information. Here is a bit of a summary.

You have a few strategies to choose from.

1 - If you are developing an SPA (or not) you may find making use of the history api useful. https://developer.mozilla.org/en-US/docs/Web/API/History

https://developer.mozilla.org/en-US/docs/Web/API/History_API

You will find plenty on SO about history api. Try starting here Preserve dynamically changed HTML on back button

Basically, by adding a listener for popstate event which fires everytime the active history entry changes : (in jQuery)

$(document).ready(function () {
    $(window).on('popstate' , function (event) {
      console.log('popstate');
      console.log(event);
      console.log(event.originalEvent);
    });
};

http://caniuse.com/#search=history

2 - add a listner for the pageshow event, will fire when a page load is completed and when session history entry is used for navigation, so basically forward & back buttons. https://developer.mozilla.org/en-US/docs/Web/Events/pageshow

$(window).on('pageshow' , function (event) {
    console.log('pageshow');
    console.log(event);
    console.log(event.originalEvent);
});

http://caniuse.com/#search=pageshow

3 - Append a hashvalues to your urls with window.location.hash = 'pageHashValue'. Listen for hashchange event and you can then act based on the #value if needed. https://developer.mozilla.org/en-US/docs/Web/Events/hashchange

This is a common approach in single page applications.

$(window).on('hashchange' , function (event) {
    console.log('hashchange');
    console.log(event);
    console.log(event.originalEvent);
    console.log(window.location.hash);
});

http://caniuse.com/#search=hashchange

Finally take note that while you, as a developer, no doubt hate the browser back button (like me) our users tend to love it. If you change the expected behavior of the back button you can also expect your user experience to be negatively affected. The best strategy is to use these events to maintain the expected behavior of the back button rather than to try and change it.

Community
  • 1
  • 1
robs
  • 840
  • 10
  • 15