and ) and provides functionality global to the document (such as obtaining the page’s URL and creating new elements in the document).” style=”margin: 0px; padding: 0px; border: 0px; color: rgb(0, 149, 221); text-decoration: none;”>
document only if you modify only the hash.
- You don’t have to change the URL if you don’t want to. In contrast, setting
window.location = "#foo"; only creates a new history entry if the current hash isn’t
- You can associate arbitrary data with your new history entry. With the hash-based approach, you need to encode all of the relevant data into a short string.
pushState() never causes a
hashchange event to be fired, even if the new URL differs from the old URL only in its hash.
The replaceState() method
history.replaceState() operates exactly like
history.pushState() except that
replaceState() modifies the current history entry instead of creating a new one.
replaceState() is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.
In Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) through Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), the passed object is serialized using JSON. Starting in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), the object is serialized using the structured clone algorithm
. This allows a wider variety of objects to be safely passed.
The popstate event
popstate event is dispatched to the window every time the active history entry changes. If the history entry being activated was created by a call to
pushState or affected by a call to
state property contains a copy of the history entry’s state object.
window.onpopstate for sample usage.
Reading the current state
When your page loads, it might have a non-null state object. This can happen, for example, if the page sets a state object (using
replaceState()) and then the user restarts her browser. When your page reloads, the page will receive an onload event, but no popstate event. However, if you read the history.state property, you’ll get back the state object you would have gotten if a popstate had fired.
You can read the state of the current history entry without waiting for a
popstate event using the
history.state property like this:
var currentState = history.state;
For a complete example of AJAX web site, please see: Ajax navigation example.