3

I want to be able to add certain behavior when a user clicks browser "back" and "forward" buttons.

Is there a way to say with JavaScript something like this:

backButton.onclick = function() {
// do something
}

forwardButton.onclick = function() {
//do something else
}

Is there a way to do that directly with JavaScript, without relying on any plugin?

KeithRules
  • 207
  • 1
  • 4
  • 14

1 Answers1

7
window.addEventListener("popstate", function(e) { // if a back or forward button is clicked

// do whatever

}

Works only in HTML5-enabled browsers, though.

For other browsers support, look into History.js

Dimitri Vorontzov
  • 7,834
  • 12
  • 48
  • 76
  • 6
    That's working great and I implemented it within moments in my code. BUT, how can I differentiate the Back button from the Forward button specifically?? Trying to detect that, I got the "e" object to appear in the console for every click on Back and Forward. Then only difference in this object between these two cases is the content of e.state - either an object or null. Although I doubt that, I have to ask - is this the indication for the difference between the buttons?? – TheCuBeMan Jun 24 '15 at 11:37
  • @TheCueBeMan, I have the same question, "How can I differentiate between the browser forward and back arrows being clicked. "popstate" detection only reveals that one or the other was clicked - not which one was clicked. I have searched extensively and I have not been able to get a single answer to this question! – Eight Lives Mar 26 '22 at 23:43