0
$(window).on('popstate', function(){
    window.history.go(-1);
});

I have a page use popstate when user click back button

but in some browser, popstate fire on page load instead back button click.

it happen in Safari and touch device.

user2178521
  • 833
  • 1
  • 14
  • 26
  • I think this will work for you. Click on [popstate-fire-on-page-load-issue][1]. [1]: http://stackoverflow.com/questions/15896434/window-onpopstate-on-page-load – Kushal Sharma Jun 20 '14 at 07:45

2 Answers2

1

The easiest hack/solution, is to add the popstate listener right after the initial page load, in a setTimeout.

 setTimeout( function() {
    window.addEventListener( 'popstate', myPopStateHandler, false );
  }, 500 );

I’m weary of throwing a setTimeout in for a resolution, always seems like a kludge. But for now, hey it works.

Clavat
  • 107
  • 1
  • 8
-1

Adding a flag to detect page load fixed this for me.

Edit: added Safari browser detection, otherwise first click of back button won't trigger popstate event in Firefox or Chrome.

var isSafari = /^((?!chrome).)*safari/i.test(navigator.userAgent),
    firstLoad = true;
$(window).on('popstate', function(){
    if (isSafari && firstLoad) {
        firstLoad = false;
        return;
    } else {
        // run your popstate code
    }
});
marissajmc
  • 2,583
  • 1
  • 22
  • 19