About HTML5 History API
About HTML5 History API
HTML5 enhanced the history API. In SPAs, there are two ways to change the URL without refreshing the page:
- Modify the page’s hash value
- Use the enhanced
pushStatefrom HTML5
Let’s start with hash, which works in all browsers.
Hash is what we used to call an anchor. We’re not unfamiliar with it. We can set it via:
location.hash="212345"
This sets the URL’s hash value. The result looks like:
In HTML, we can also modify the hash using an anchor tag:
<a href="#123456"></a>
When we modify the hash, a corresponding event is triggered:
window.onhashchange = function(){
//do something
}
That’s enough about hash. Now let’s talk about pushState.
pushState is a method under the history object.
So we call it like this:
history.pushState()
The pushState family has two methods and one event:
history.pushState(state, title, url);
history.replaceState(state, title, url);
window.onpopstate
pushState
pushState takes three parameters:
state: You can put any data you want here. It will be attached to the new URL as supplementary information for that page.
title: As the name suggests, this is document.title. However, this parameter currently has no effect — browsers choose to ignore it.
url: The new URL, which will be displayed in the address bar.
After pushState runs, the history is recorded.
replaceState
It also takes three parameters, and works the same as above.
The only difference is that it does not record history.
window.onpopstate
history.pushState() does not trigger this event.
history.replaceState() does not trigger this event either.
This event is triggered when the page navigates forward or backward.
The event provides a PopStateEvent object, from which you can get a lot of information about the state.