Skip to content Skip to sidebar Skip to footer

Back Button / Backspace Does Not Work With Window.history.pushstate

I have made a solution for my website which includes using ajax to present the general information on the website. In doing this, I am changing the URL every time a user loads some

Solution 1:

pushState alone will not make your page function with back/forward. What you'd need to do is listen to onpopstate and load the contents yourself similar to what would happen on click.

var load = function (name, skipPushState) {
  $("#hideGraphStuff").hide();
  // pre-load, etc ...

  $.post("pages/getPriceDeckData.php",{data : name}, function(data){
    // on-load, etc ...// we don't want to push the state on popstate (e.g. 'Back'), so `skipPushState`// can be passed to prevent itif (!skipPushState) {
      // build a state for this namevar state = {name: name, page: 'Price Deck'};
      window.history.pushState(state, "Price Deck", "?p=priceDeck&dN="+ name);
    }
  });
}

$(document).on("click", ".priceDeckLink", function() {
  var name = $(this).text();
  load(name);
});

$(window).on("popstate", function () {
  // if the state is the page you expect, pull the name and load it.if (history.state && "Price Deck" === history.state.page) {
    load(history.state.name, true);
  }
});

Note that history.state is a somewhat less supported part of the history API. If you wanted to support all pushState browsers you'd have to have another way to pull the current state on popstate, probably by parsing the URL.

It would be trivial and probably a good idea here to cache the results of the priceCheck for the name as well and pull them from the cache on back/forward instead of making more php requests.

Solution 2:

This works for me. Very simple.

 $(window).bind("popstate", function() {
    window.location = location.href
  });

Post a Comment for "Back Button / Backspace Does Not Work With Window.history.pushstate"