Joe Yates' Blog

Programming and DevOps

HTML History API

The HTML5 history API allows AJAX-based sites to avoid "breaking the back button". Every time you update the page, you store the new content is the window.history object. When the user presses the back button, you retrieve the current item from window.history and update the page with it.

What follows is an "all-in-one page" Sinatra/jQuery program. You can find the code here.

Run it like this:

run the program - run.sh
1
  $ ruby history_api.rb

The program allows you to browse back and forwards through numbered pages.

When the first page is shown, the initial content of the container is stored in the history object:

Replace State - replace_state.js
1
history.replaceState( $( '#container' ).html(), '', location.href );

As you select links, only the content of the ‘container’ DIV gets updated. An AJAX call is made to get the content, which is stored in the history object:

onClick Callback - on_click.js
1
2
3
4
5
6
   var anchor = this;
    $.get( this.href, function( data ) {
      history.pushState( data, '', anchor.href );
      $( '#container' ).html( data );
      updateLinks( anchor.getAttribute( 'data-number' ) );
    } );

Each time the back button is pressed, the content is retrieved and placed in the container:

onpopstate - onpopstate.js
1
2
3
onpopstate = function( event ) {
  $( '#container' ).html( event.state );
};

Notice that pressing the forward and back buttons updates the page correctly without needing to call the server.