Back / Backspace button does not work with window.history.pushState

I made a solution for my website that involves using ajax to present general information on the website. In doing so, I change the URL every time a user loads certain content using the window.history.pushState method. However, when I click backspace or click backwards, the contents of the old URL are not loading (however, the URL is loaded).

I tried several solutions presented on SO with no luck.

Here is an example of one of the ajax functions:

$(document).ready(function(){ $(document).on("click",".priceDeckLink",function(){ $("#hideGraphStuff").hide(); $("#giantWrapper").show(); $("#loadDeck").fadeIn("fast"); var name = $(this).text(); $.post("pages/getPriceDeckData.php",{data : name},function(data){ var $response=$(data); var name = $response.filter('#titleDeck').text(); var data = data.split("%%%%%%%"); $("#deckInfo").html(data[0]); $("#textContainer").html(data[1]); $("#realTitleDeck").html(name); $("#loadDeck").hide(); $("#hideGraphStuff").fadeIn("fast"); loadGraph(); window.history.pushState("Price Deck", "Price Deck", "?p=priceDeck&dN="+ name); }); }); 

Hope you guys can help :)

+8
javascript jquery
source share
1 answer

pushState will not do your page backward / forward pushState its own. What you need to do is listen onpopstate and load content similar to what happens when clicked.

 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 (eg 'Back'), so `skipPushState` // can be passed to prevent it if (!skipPushState) { // build a state for this name var 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 slightly less supported part of the history API. If you want to support all pushState browsers, you will have to have a different way of pushState current state using the tooltip, possibly by parsing the URL.

It would be trivial and probably nice to also cache priceCheck results for the name and pull them back / forth from the cache instead of making more php requests.

+15
source share

All Articles