HTML History API

2011/07/18

The Example App

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:

$ 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:

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:

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 = function(event) {
  $('#container').html(event.state);
};

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