English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML5 History Record API

HTML5Usage methods of the history record API, online instance demonstration HTML5How to use the history record API, browser compatibility, syntax definition, and detailed information about its attribute values.

HTML5The history record API allows you to access the browser's navigation history through JavaScript. HTML5The history record API is very useful in single-page web applications. Single-page web applications can use HTML5The history record API to make some state "taggable" in the application. Later, I will return to how to use the history record API to establish taggable states in a single-page application.

History Stack

Browsing history is composed of a stack of URLs. Each time the user browses the same website, the URL of the new page will be placed at the top of the stack. When the user clicks the "Back" button, the pointer in the stack will move to the previous element in the stack. If the user clicks the "Forward" button again, the pointer will move forward to the top element of the stack. If the user clicks "Back" and then clicks a new link, the top element of the stack will be overridden by the new URL.

This is an example of a history stack:

http://myapp.com/great-new-story.html
http://myapp.com/news.html
http://myapp.com

The last page accessed in the above history stack is http://myapp.com/great-new-story.html. If the user clicks the "Back" button, the pointer in the history stack will move back http://myapp.com/news.html. If the user clicks the "Forward" button, the pointer of the history stack will move forward http://myapp.com/great-new-story.html, but if the user clicks another link (in http://myapp.com/If the link on the news.html page is clicked, then the URL of the link will be http://myapp.com/news.html overrides in the history stack.

HTML5The history API allows web applications to access the history stack.

HTML5Security restrictions of the history API

HTML5The history API only allows web pages to access a part of the browser history that is located in the same domain as the web page itself. This restriction is necessary for security reasons, so web pages cannot see which other websites the user has visited.

Similarly, HTML5The history API does not allow web pages to push URLs onto the history stack that are not in the same domain as the web page. This restriction ensures that when the user starts typing a web page, the web page cannot pretend to have redirected the user to, for example, Paypal and sniff their username/passwords, etc.

History object

You can access the browser history through the history object, which can be used as a global object in JavaScript (it is actually window.history).

The history object includes the following functions-Including the history API:

  • back()

  • forward()

  • go(index)

  • pushState(stateObject, title, url)

  • replaceState(stateObject, title, url)

The back() feature moves the browser history back to the previous URL. Calling back() has the same effect as the user clicking the browser's "Back" button.

The forward() feature moves the browser history forward to the next page in the history. Calling forward() has the same effect as clicking the browser's "Forward" button. It is only possible to go forward if the history is already pointing to the latest URL in the browser history.

The go(index) function can move the history forward or backward based on the index you pass as a parameter to the go() function. If you call go() with a negative index (for example, go(-1)) will make the browser return to the history. If you pass a positive index to the go() function, the browser will move forward in the browser history (for example, go(1)) indicates the step in the history to go forward or backward in the browser history. For example1,2,-1,-2...

The pushState(stateObject, title, url) function pushes a new URL onto the history stack. This function has three parameters. The url is the URL that is pushed onto the history stack. The title parameter is usually ignored by the browser. The stateObject is, when a new URL is pushed onto the history stack, it is the object that is dispatched along with the event. It stateObject can contain any data you want. It is just a JavaScript object.

The function replaceState(stateObject, title, url) works similarly to the pushState() function, but it replaces the current element in the history stack with a new URL. The current element is not necessarily the most important element. It is the currently pointed element, which can be any element in the stack, if the back(), forward(), and go() functions have already been called on the history object.

history API example

Now let's look at some examples of how to use HTML5example of the history API.

back() and forward()

First let's see how to use the back() and forward() functions to move back and forth in the history:

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

Remember, the history object is located within the window object, so you can also write:

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

However, since the window object is the default object, it can be omitted. In the rest of this tutorial, I will ignore the object.

Remember, you cannot move into the history unless you (or the user) go back in the history first.

go()

Now let's see how to use the go() function to perform actions similar to the back() and forward() functions. First, this is the previous step you use to browse the history backward with go():

history.go(-1);

To move back two steps, you can use-2Parameters are passed to the go() function as shown below:

history.go(-2);

Similarly, to make the history move forward, you can pass a positive index to the go() function. Here are examples of two steps forward and two steps in history:

history.go(1);
history.go(2);

Of course, if you execute these two lines at the same time, the browser history will move forward in total3steps.

pushState()

To push a state into the history stack, call the pushState() function of the history object. Here is an example of pushState():

var state = {};
var title = "";
var url = "next"-page.html";
history.pushState(state, title, url);

This example pushes a new URL to the history stack. This will also change the URL in the browser's address field, but it will not cause the browser to attempt to load the URL.

replaceState()

The replaceState() function replaces the current history element in the history stack. If the user has moved it back to the history using the 'back' button, this may not be the most important element. Here is an example of replaceState():

var state = {};
var title = "";
var url = "another-page.html";
history.replaceState(state, title, url);

Replacing the state will also change the URL in the browser's address field, but will not cause the browser to load the URL. The page with the replaced URL is still retained in the browser.

Browser history changes

HTML5The History API allows web pages to listen for changes in the browser history. Security restrictions also apply here, so changes in history that cause the URL to go beyond the domain of the web page will not be notified to the web page.

To listen for changes in the browser history, set an onpopstate listener on the window object. Here is an example of a browser history event listener:

window.onpopstate = function(event) {
    console.log("History changed to:") + document.location.href);
 }

The onpopstate event handler will be called each time there is a change in the browser history within the same page (browser history, page pushed to the history stack). The response to historical change events may be to extract parameters from the URL and load the corresponding content into the page (for example, through AJAX).

Note: Only changes that cause any 'back' or 'forward' buttons, or the corresponding historical navigation functions back(), forward(), and go() will trigger the onpopstate event listener. Calling pushState() and replaceState() functions will not trigger historical change events.

Using History API in practice

When a new URL is pushed into the history stack, the URL in the browser's address field will change to the new URL. However, the browser will not attempt to load the URL. It will only display the URL and push it into the stack, as if the browser has visited the page, but the page with the new state pushed is still retained in the browser.

Pushing a new URL to the history stack is a useful method to make a specific state bookmarkable in a single-page application (SPA). For example, in a single-page online store, the application's URL might be:

http://myshop.com

This application may be able to display products to users on the same page, but how can users send links to specific products to their friends?

The solution is that when loading a new product, the single-page application pushes the new URL into the history stack. This does not cause the new URL to be loaded, but does make the new URL visible in the browser's address field. From here, it can be added as a bookmark or copied and pasted into emails, etc. Here is an example of such a URL that can be bookmarked:

http://myshop.com?productId=234

Or, perhaps a more readable URL:

http://myshop.com/products/234

Or perhaps a version slightly more than REST (also mentioned product types):

http://myshop.com/products/books/234

After pushing the URL into the browser's history, the web store page will load the corresponding product via AJAX and display it to the user.

If the user clicks the "Backward" button, the onpopstate event handler will be called. Then, the web page should check what the new URL is, and if the URL is returned, load the homepage corresponding to the product or application at http://myshop.com.

This is an HTML5This code example demonstrates the principle of loading data into the browser using AJAX:

<a href="javascript:push('http://myshop.com/books/123')">
    Book 123
</a><br/>
<a href="javascript:push('http://myshop.com/apps/456')">
    App 456
</a>
<script>
function loadUrl(url) {
    console.log("loading data from url: " + url);
}
function push(url) {
    history.pushState(null, null, url);
    loadUrl(url);
}
window.onpopstate = function(event) {
    console.log("history changed to: " + document.location.href);
    loadUrl(document.location.href);
}
</script>

This example includes two links with JavaScript Click event listeners. After clicking one of the links, the corresponding URL will be pushed into the history stack and then loaded into the browser.

This example also includes a onpopstate event listener. When the user clicks the "Backward" or "Forward" button, this event listener will load any URL currently displayed in the browser's address field.

Configure the server

If the user clicks the link and "Backward" /Click the "Forward" button, and the example displayed previously will take effect. However, what should be done if the user sends the URL to a friend or adds it as a bookmark and accesses it later?

If the user tries to access a tagged URL, http://myshop.com/books/123the browser will request the URL from the web server. The web server needs to know that it must send back the same single-page application http://myshop.com. You will need to configure the web server to perform this operation.

Similarly, single-page web applications must check the URL used when first loaded and use that URL to determine the content to be loaded and displayed. Therefore, if the single-page application has loaded the URL, then myshop.com/books/123This application should load the corresponding product and display it. This URL check must be performed during the initialization of the single-page application.

Browsers support HTML5History API support

At the time of writing this article, all modern browsers (IE, Safari, Chrome, Firefox) support HTML5History API.