Search code examples
jqueryajaxhtmlbrowser-history

Re-using HTML history state when browser previous/next buttons are clicked


I'm trying to implement the HTML5 history feature to perform AJAX loading of page content. So far my JS looks like this:

// saving current page to history
var current_url = "page1"    
var page_content1 = $('body').html();
history.pushState({page_content: page_content}, current_url, current_url);

// loading new page with AJAX
var new_url="page2"
$.getJSON(new_url,get_data,function(data){
    $('body').html(data.page_content);

    var page_content2 = $('body').html();
    history.pushState({page_content: page_content2}, new_url, new_url);
}); 

-OK: when the JS is executed the content of "page2" is properly loaded via AJAX into the body and the browser URL is changed from "page1" to "page2".
-OK: when I click the previous browser button, the browser URL is changed back from "page2" to "page1"
-NOT OK: however when I click the previous browser button, the page content is not changed to what it used to be for "page1".

Q: What events should I bind for the previous/next browser buttons, and what history method should I use to retrieve the state data after pressing those buttons?


Solution

  • I ended up using history.js which relies on the window 'statechange' event to handle interactions with browser previous/next buttons and the getState() method to retrieve the state data.