JavaScript or jQuery browser back button click detector

Nil Pun picture Nil Pun · Jul 11, 2013 · Viewed 201.9k times · Source

Could someone please share experience / code how we can detect the browser back button click (for any type of browsers)?

We need to cater all browser that doesn't support HTML5

Answer

Benny Neugebauer picture Benny Neugebauer · Oct 17, 2013

The 'popstate' event only works when you push something before. So you have to do something like this:

jQuery(document).ready(function($) {

  if (window.history && window.history.pushState) {

    window.history.pushState('forward', null, './#forward');

    $(window).on('popstate', function() {
      alert('Back button was pressed.');
    });

  }
});

For browser backward compatibility I recommend: history.js