How to Modify the Browser History in Complex HTML5 and JavaScript Applications

Don’t you love snappy titles?!

Consider a sophisticated application such as webmail client. In essence, it’s a complex JavaScript program running on a single HTML page. The user loads the URL and is presented with a list of emails. They click a title and the email content is retrieved using Ajax and displayed. They now want to return to the email list; what do they do?…

…click the browser’s back button.

Bang. The application closes and returns to the page they were viewing prior to accessing the application. Or, if it’s a new browser tab, the back button is disabled and can’t be clicked.

So we have a problem. Our webmail client doesn’t support the one browser control most users understand. There are solutions. Some involve changing the hash mark (#name) in the URL so the state can be retained. It’s not perfect, but works in all browsers.

Fortunately, the problem has been addressed with the HTML5 history.pushState and history.replaceState methods in conjunction with the window.onpopstate event.

Try the history.pushState() demonstration page…

The technique is refreshingly simple:

  1. When the state changes, e.g. the user opens an email, history.pushState() is passed state information and executed. This enables the back button but — importantly — does not move the user from the page.
  2. You can run history.pushState() as many times as necessary, or modify the current state using history.replaceState().
  3. When the user clicks back (or forward), the window.onpopstate event is fired. A handler function can retrieve the associated state and display the appropriate screen.

The downside? Forget IE compatibility until v10 arrives. If you need to support IE9 and below, there are a number of shims including History.js and HTML5-History-API.

Let’s write some code. Assume you’ve just displayed the result of an Ajax request:


// Ajax request
...
// display result
...

// modify history
history.pushState(obj, title, url);

Where:

  • obj is any JavaScript object. You could use this to retain state information, e.g. { “view”: “EMAILCONTENT”, “item”: 123 };
  • title is an optional title
  • url is an optional URL. The URL can be anything — the browser won’t jump to that page, but could if the user reloaded the page or restarted their browser. In most cases, you’ll want to use parameters or a hash name, e.g. ?view=EMAILCONTENT&item=123; your application could analyze these values on start-up and return to the same place.

history.replaceState() has identical arguments and is only used if you want to replace the current state with a new one.

You now need a handler function which runs when the window popstate event fires following the browser’s back or next button being clicked:


window.addEventListener("popstate", function(e) {

	// URL location
	var location = document.location;

	// state
	var state = e.state;
	
	// return to last state
	if (state.view == "EMAILCONTENT") {
		...
	}

});

The URL location can be determined with document.location (document.location.search and document.location.hash return the parameters and hash name respectively).

The historic state object set by pushState() or replaceState() is obtained from the event object’s state property. You can use the information to display the appropriate screen.

Try the history.pushState() demonstration page…

Click the history.pushState button a few times then hit back to see what happens in the log.

Very useful. Have you encountered back and next button issues in your web application?

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Patrick

    It’s nice to see that there’s a standard way of doing this now, but as always browser incompatibility and the maddeningly slow pace of end users upgrading to modern browsers will severely limit the usefulness of this feature for the next few years.

    Until the majority of users are on a modern browser with support for the history API, location.hash is going to remain the answer to this problem (things like history.js use location.hash as a HTML4 fallback). And really, if you’re going to be using location.hash for many/most users, you may as well use it for all of them to simplify debugging and reduce inconsistencies between browsers. I’ll set myself a reminder to revisit this in 2016, when browser support might be widespread enough to justify the switch from location.hash.

    • http://www.optimalworks.net/ Craig Buckler

      I agree it’s frustrating, although the technique is more flexible than location.hash. However, unlike other unsupported APIs, this one isn’t a show-stopper. You could adopt it and accept that the majority of IE users won’t be able to use the browser back/forward buttons.

  • Carl

    Great article.

    As of now, our only solution has been to open the application in a new window, passing parameters to remove entirely the buttons bar. Not very elegant obviously.

    This is welcome news, even if IE will be late to the party again :/

    • http://www.optimalworks.net/ Craig Buckler

      Take a look at using history.pushState() with shims or adopting location.hash. Opening other windows won’t always work: popups can be disabled and mobile browsers will ignore it. You’re also removing the one control users understand.

      Alternatively, look at IE-specific features such as pinned web applications. They permit you to remove the back/forward buttons.

  • http://devseo.co.uk Alex Hall

    I had the chance to use this on an internal system at work a while ago and it’s just brilliant! I use tabbed browsing, but it just loads up a different content section when a tab is clicked, which was great until someone reloaded the page. Adding the pushState stuff allowed me to change the URL without changing the page, which meant with a refresh or closing and reopening the tab, the same content panel was reopened. Once it’s more widely supported I’ll be using it everywhere!