JavaScript or jQuery browser back button click detector

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

Leave a Comment