Take the 2-minute tour ×

I have been trying to get the forward an back browser buttons to work on a small site using pjax and have come up with the following code to handle class changes and fading in and out the various overlays.

However I have found that Chrome and Safari treats the initial page load as a popstate and so it is causing me grief. Is there anyway to stop this?

$(window).on("popstate", function() {
  if ($('body').hasClass('info')) {

  } else if ($('body').hasClass('work')) {

  } else {
share|improve this question

3 Answers 3

Tag the state when you call pushState(), then ignore all popstate events that don't have your tag. e.g.

history.pushState({ myTag: true }, ...)

$(window).on("popstate", function(e) {
  if (!e.originalEvent.state.myTag) return; // not my problem
  // rest of your popstate handler goes here

Don't forget to call replaceState at page load so that you can handle the popstate when you get back to the initial page load.

$(function() { history.replaceState({ myTag: true }); });
share|improve this answer
I actually found that the solution is within pjax. So instead of doing –  Sam Quayle May 26 '12 at 20:23
That's the only solution i found that works after the first call of a page, after a reload and in gecko/webkit/trident. Plus without changing the behavior browsers calling popstate! Great solution. Thanks! –  griffla May 16 '13 at 18:31
up vote 3 down vote accepted

I actually found the solution within pjax itself.

Instead of doing:

$(window).on('popstate, function() { ... 

which fired the popstate on the initial page load I did:

$(window).on('pjax:popstate, function() {...  
share|improve this answer
Doesn't work for me in Chrome 39 –  s29 Dec 17 at 1:08

The best long term fix is to up-vote https://code.google.com/p/chromium/issues/detail?id=63040 to get Google to fix this. They've known they're out of compliance with the HTML5 spec for about two years now.

share|improve this answer
It says Status: Fixed and a comment there: "Still not landed on Chrome 32 stable, fixed on Chrome Canary 34." - Feb 10, 2014. –  marczking Apr 28 at 11:57

Your Answer


