How to manage the back button with JavaScript

One major issue with JavaScript-based applications is that they break the Back button. If you update content on the page with JavaScript rather than loading a new page from the server, no entry made is in the browser history; so when the user clicks Back, expecting to go back to the previous state, they end up at the previous site instead.

Drag and drop is a great way for users to interact with your web applications. But the usability gains will be lost if, after spending time moving through your application, users click the Back button expecting to go back a page and instead go back to their Start screen. In this article “Hello! HTML5 & CSS3” author Rob Crowther shows you how to use the HTML5 history API to avoid that fate.

The problem can be demonstrated simply. All you need is a function that updates the page in response to user activity:

var times = 0;
function doclick() {
times++;
document.getElementById('message').innerHTML =
'Recorded <b>' + times + '</b> clicks';
}

and a little markup:

<div onclick="doclick();">Click Me</div>
<div id="message">Recorded <b>0</b> clicks</div>

In real life, your web page would be doing something more complicated, like fetching new content from the server via AJAX, but a simple update is enough to demonstrate the concept. Let’s see what happens when the user visits the page.

  1. The user starts on their home page and decides to visit the amazing Click Me application they’ve heard about.
  2. They type in the URL or follow a link from an email to get to the Click Me page.
  3. After a few seconds of enjoyable interaction, the page state has changed several times.
  4. But when the user clicks the Back button in the browser, they find that instead of going back to a previous page state, they leap to their home page.

The doclick() function can be updated to take advantage of the history API. Each time the page is updated it will also set the location.hash:

function doclick() {
times++;
location.hash = times;
document.getElementById('message').innerHTML =
'Recorded <b>' + times + '</b> clicks';
}
  1. The user arrives at the Click Me page as before.
  2. Notice that now the URL is updated after every click—”#” has appeared at the end of it.
  3. Clicking the Back button now takes the location back to #2, demonstrating that page states have successfully been added to the history. But note that clicking the Back button doesn’t automatically return the page to its previous state.

Updating page state

Updating the history is only part of the problem; you also need to be able to update the state of the page to match the state in the history.

Because you’re the one managing the history, it’s up to you to manage the page state. In order to update your page in response to location.hash being changed, you can listen to the hashchange event:

function doclick() {
times++;
location.hash = times;
}
window.onhashchange = function() {
if (location.hash.length > 0) {
times = parseInt(location.hash.replace('#',''),10);
} else {
times = 0;
}
document.getElementById('message').innerHTML =
'Recorded <b>' + times + '</b> clicks';
}

The doclick() function is now only responsible for updating the times variable and changing the hash. The hashchange event is on the window object; when it takes place, you check that the hash exists. In a real application, you’d also want to check that it had a valid value. Next, you set the value of times to be the number in the hash. Finally, you update the document to reflect the correct page state. Let’s look at this new code:

  1. As before, the hash in the URL is updated as the user clicks.
  2. But now, when the Back button is clicked, the onhashchange function is triggered and the page state is reset to match the URL.

Using location.hash

The location.hash property and the associated hashchange event are useful if you want to tag particular views of your application and allow the user to navigate between them. Google Mail uses this approach by allowing you to navigate between your inbox (#inbox), contacts (#contacts), and other views—if you have a Gmail account, look at what happens to the URL as you navigate to various different pages and then click back.

But as far as state information goes, the hash only lets you store a string. You could encode a more complex object, but the URL would quickly become long and unwieldy and wouldn’t be memorable for your users. If you need more complex information stored as part of the history, a better approach would be to use the hash as a key to pull further state information out of some store. Although you could roll your own approach to this, HTML5 has provided an API to do it for you through the history.pushState() method and the popstate event. These methods allow you to save and reload a complex object.

Summary

You’ve learned that managing the browser’s history allows you make the Back button behave in a more sensible way in the context of your application, while the microdata API gives you access to structured semantic information in page contents.

What uses do you envisage for this technique? Have you developed a different method? Let us know in the comments.

Featured image/thumbnail, go back image via Shutterstock.

Rob Crowther

Rob Crowther

Rob Crowther, Joe Lennon, Ash Blue and Greg Wanish's HTML5 in Action is available in PDF, ePub, and Kindle from manning.com/crowther2/. The paperback will be released Nov 2013. Save 50% with Promo code wdcrowther2 until 10/19. Offer valid only at manning.com.

Join to our thriving community of like-minded creatives!