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

Share this article

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?

Frequently Asked Questions (FAQs) about JavaScript History PushState

What is the main function of JavaScript History PushState?

The JavaScript History PushState is a method that allows you to manipulate the browser history. It is part of the History API and it enables you to add history entries. This is particularly useful when you want to create a single-page application that can change the URL without reloading the page. It helps in maintaining the user experience and the state of the application even when the user navigates through the browser’s forward and back buttons.

How does JavaScript History PushState work?

The JavaScript History PushState works by taking three parameters: a state object, a title (which is currently ignored by most browsers), and a URL. When the pushState method is invoked, it creates a new history entry in the browser’s history stack. This new entry is associated with the specified state object and URL. When the user navigates to this new entry, the popstate event is fired, and the state object is passed back to the application.

Can I use JavaScript History PushState in all browsers?

The JavaScript History PushState is widely supported in all modern browsers. However, it is not supported in Internet Explorer 9 and earlier versions. Therefore, if you are developing applications for older browsers, you might need to use a polyfill or fallback to hash-based URLs.

What is the difference between pushState and replaceState methods in JavaScript?

Both pushState and replaceState methods are part of the History API and are used to manipulate the browser history. The main difference between them is that pushState creates a new history entry and adds it to the history stack, while replaceState modifies the current history entry without adding a new one to the stack.

How can I handle the popstate event in JavaScript?

The popstate event is fired whenever the active history entry changes. If the history entry was created by pushState, the state object associated with that entry is passed back to the application. You can handle the popstate event by adding an event listener to the window object and defining a function that will be executed when the event is fired.

What is the state object in JavaScript History PushState?

The state object is a JavaScript object associated with a history entry. This object can contain any kind of data that you want to associate with the history entry. When the user navigates to the history entry, the state object is passed back to the application, allowing you to restore the state of the application.

Can I change the URL without reloading the page using JavaScript History PushState?

Yes, one of the main advantages of using JavaScript History PushState is that it allows you to change the URL without reloading the page. This is particularly useful when you want to create a single-page application that can change the URL to reflect the current state of the application.

What is the role of JavaScript History PushState in single-page applications?

In single-page applications, JavaScript History PushState plays a crucial role in maintaining the user experience. It allows you to change the URL to reflect the current state of the application without reloading the page. This means that the user can navigate through the application using the browser’s forward and back buttons without losing the application state.

How can I use JavaScript History PushState to create a navigation system?

You can use JavaScript History PushState to create a navigation system by adding history entries for each navigation action. When the user navigates to a history entry, you can use the state object associated with that entry to restore the state of the application. This allows you to create a seamless navigation experience without reloading the page.

What are the limitations of using JavaScript History PushState?

While JavaScript History PushState is a powerful tool for manipulating the browser history, it has some limitations. For example, it is not supported in Internet Explorer 9 and earlier versions. Also, it can only add history entries for the same origin, which means you cannot use it to add history entries for different domains.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

backbrowserhistoryHTML5 Dev CenterJavaScriptnextstate
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week