Is there a way to catch the back button event in javascript?

Viewed 108959

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.

5 Answers

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.

onLocationChange may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.

Related