Javascript – way to catch the back button event in javascript


Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.

Best Solution

Use the hashchange event:

window.addEventListener("hashchange", function(e) {
  // ...

If you need to support older browsers, check out the hashChange Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.