TOC

The community is working on translating this tutorial into Dutch, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

JavaScript for Web: The BOM:

The History object

As a part of the global window object, you'll find the History object. It allows you to work with the browsing history for the current page, with several interesting properties and methods.

You can access the history through the history property of the window object, like this:

window.history

But since window IS the global object, you can skip the window. prefix if you want to and just access the history object directly.

With this in place, let's go through the most interesting properties and methods of the history object. For the complete list of object members, please have a look at the documentation.

History properties

Only a few properties exist on the history object.

history.length

The length property will basically tell you how many pages have been visited within the current window/tab. So, if you open a browser and access this page directly, the returned value will be 1. On the other hand, if you accessed this page by clicking a link on another page, the returned value will be 2 or more. Accessing the property is simple as always:

alert(window.history.length);

Notice that some browsers will have a start page, listing the most recently visited pages etc. This is likely also a webpage, so if you open this start page and then move onto another page, e.g. this one, the length will return 2 instead of 1.

history.state

We'll talk about the state property later in this article, when we walk though the pushState() and replaceState() methods.

History methods

With the most important properties covered by now, let's talk about the methods found on the History object.

history.back() / history.forward()

These two methods can make the browser go back and forward in the browsing history, if possible. Simply call them, like this:

window.history.back();
window.history.forward();

They will make the browser take one step back/forward, if possible - if not, they will simply do nothing.

history.go()

This method will allow you to go to a specific position in the current browsing history. You will usually provide a number as a parameter, either positive (forward) or negative (backward). If you don't provide a parameter, it will simply reload the current page.

Here's an example, where we move two steps back in the browsing history:

window.history.go(-2);

Or you can do this, if you want to go one step forward (basically the same as calling forward()):

window.history.go(1);

History state (history.pushState() / history.replaceState())

This is probably the most interesting part of the History object, so I want to dig a little bit deeper here to tell you about the state concept, how it works, and the two methods involved.

By utilizing the state of the browser, and the above mentioned methods, you are able to manipulate the history of the browser as well as the current URL, without causing a redirect or reload. This can come in handy if you're building an app-like experience, where you, for instance, load content dynamically based on the URL. By using the state, you can change the URL, load new content and then tell the browser that the state has changed, allowing the user to navigate back and forth between the states.

The most interesting member is the pushState() method. It takes three parameters, but the middle one is only there for historical reasons and you should just pass an empty string. So, the interesting parameters are the first and the third. Here's an example of how you may create a function for dynamically loading content and then calling the the pushState() method to let the browser know that the state has changed:

function ShowContent(id)
{
	var url = id + ".html";
	var stateData =
	{
		contentId: id,
		contentUrl: url
	};
	window.history.pushState(stateData, "", url);	
	// Load the content here...
}	

Notice how we create a data object for storing information about the state that we are pushing (the stateData object) and then the new URL, which will be reflected in the address bar of the browser. At the end of the function you can load the data dynamically and place it within the page accordingly.

The window.onpopstate event

When the pushState() method is called, a new entry is created in the browser history, meaning that you can now navigate back from the current state to the previous state. Whenever the state changes due to a user action, e.g. because the user navigates back to a previous state, the window.onpopstate event is called and the data you pushed (the stateData object) is passed to this event, allowing you to react to the data.

With that in mind, I have expanded the example above a bit, to make a crude version of a dynamic content page based on the history state. It's definitely not complete, but it will give you an idea of how the concept of the browser history state works:

<a href="#" onclick="ShowContent('products');">Show products</a>
<a href="#" onclick="ShowContent('orders');">Show orders</a>
<a href="#" onclick="ShowContent('customers');">Show customers</a>

<div id="divDynamicContent"></div>

<script>

	window.onpopstate = function(event)
	{
		if(event.state != null)
		{
			console.log(event);
			LoadContent(event.state.contentId);
		}
	};

	function ShowContent(id)
	{
		var url = id + ".html";
		var stateData =
		{
			contentId: id,
			contentUrl: url
		};
		window.history.pushState(stateData, "", url);	
		LoadContent(id);
	}	

	function LoadContent(id)
	{
		// Load the dynamic content here
		document.getElementById("divDynamicContent").innerHTML = "Dynamic content loaded: " + id
	}
</script>

Notice that because of the way we integrate code examples into the page (using iframes), you won't be able to run this example directly, but feel free to copy and test it on your own server.

Summary

After reading this article, you should have a good idea about how the History object works and how you can use it to work with the browser history related to the browsing session of the user. We've talked about pretty much all properties and methods for this object, but as always, be sure to check out the documentation for the full reference.