Mark Greenwood Team : Web Development Tags : Web Development

HTML5 history API

Mark Greenwood Team : Web Development Tags : Web Development

A little used feature of HTML5 is the HTML5 history API - a new standardised way to manipulate the browser history.

Why is it there?

Why would you want manipulate the browser history? Navigating away from a page has always added (and will always add) to the browser history, so why would you manually change the browser location? In recent years developers have found new ways to dynamically generate and manipulate the content on a page without actually navigating away from a page. The upside of this is that the browser just gets what it needs and doesn't jump around as it slowly reloads the entire page just to get a small updated piece of content. The downside is that the URL doesn't change and so you can't effectively bookmark it. Long and convoluted solutions have been developed but, they are long and convoluted.

How is it done?

The HTML5 history API contains just a couple of new methods to update the history and it adds just a single event (onpopstate) to the window object.

Basically, we "push" a new url onto the history stack. When the user navigates "back" or "forward" using the browser's history controls, it fires off the onpopstate event, allowing the developer to reload the content that was displayed at that time. The browser url changes to reflect that state and if you reload the browser, it requests this URL. The server/javascript can serve up the appropriate content.

It's as easy as:
history.pushState(data, title [, url ])

data = any data related the history state.
title = the title that will appear in your browser's history listing.
url = the new url of the new history item.

Further reading

More detailed information can be found here:
Manipulating the browser history
Session history and navigation