14

I am building a Html 5 website using push state and I wondering whether its possible in javascript or JQuery to detect whether the browser's back button has been pushed. I would like to include it in an if statement like so:

if (back_btn clicked){
//do stuff
}
if (forward_btn clicked){

}
Nuvolari
  • 1,071
  • 5
  • 13
  • 29

3 Answers3

20

You're looking for the popstate event.

An example:

window.onpopstate = function(event) {
    alert("location: " + document.location);
}

Or with the ever-popular jQuery:

$(window).on('popstate',function(event) {
    alert("location: " + document.location);
});

This fires whenever history is accessed, such as back/forward. A quick note, in Chrome this also fires on the page load, so a quick way around is to check if the event is null.

if(event.originalEvent.state!=null){
    // do something
}

Another good resource is the History.js jQuery plugin, which has a fallback using hashtags and such. It also makes detection of popstate events very straightforward.

PlantTheIdea
  • 15,781
  • 5
  • 32
  • 40
2

And for AngularJS

$window.onpopstate = function(e) {
    $window.alert("location: " + $location.path());
}
0

The popstate event has state property. You should track its value to detect whether Back or Forward button was pressed.

var previousState = 0
window.addEventListener('popstate', (event) => {
  if (event.state > previousState) {
    console.log('Forward button pressed')
  } else {
    console.log('Back button pressed')
  }
  previousState = event.state
})
Ilyich
  • 3,530
  • 1
  • 29
  • 23