MDN will be in maintenance mode on Thursday September 21st, starting at 10 AM Pacific / 5 PM UTC, for about 1 hour.

翻译正在进行中。

DOM window 对象通过 history 对象提供了对浏览器历史的访问。

它暴露了有用的方法和属性,让您来回滚动用户的历史记录,以及 - -从HTML5开始- - 操纵历史堆栈的内容。

穿行 history

使用 back(), forward() go() 方法来完成用户历史记录的向后和向前移动。

向前和向后移动

向后移动历史记录:

window.history.back();

这和用户点击浏览器回退按钮的效果相同。

类似地,你可以向前移动(就像用户点击前进按钮):

window.history.forward();

跳转到 history 中指定的一个点

你可以用 go() 方法载入到会话历史中的某一特定页面, 通过与当前页面相对位置来标志 (当前页面的相对位置标志为0).

向后移动一个页面 (等同于调用 back()):

window.history.go(-1);

向前移动一个页面, 等同于调用了 forward():

window.history.go(1);

类似地,你可以传递参数值2并向前移动2个页面,等等。

您可以通过查看长度属性的值来确定的历史堆栈中页面的数量:

var numberOfEntries = window.history.length;
注意: IE 支持传递URLs作为参数给 go(); 这在Gecko是不标准且不支持的。

添加和修改历史记录中的条目

HTML5引入了 history.pushState() 和 history.replaceState() 方法,它们分别可以添加和修改历史记录条目。这些方法通常与window.onpopstate 配合使用。

Using history.pushState() changes the referrer that gets used in the HTTP header for XMLHttpRequest objects created after you change the state. The referrer will be the URL of the document whose window is this at the time of creation of the XMLHttpRequest object.

pushState() 方法的例子

假设在 http://mozilla.org/foo.html 中执行了以下 JavaScript 代码:

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

这将使浏览器地址栏显示为 http://mozilla.org/bar.html,但并不会导致浏览器加载 bar.html ,甚至不会检查bar.html 是否存在。

假设现在用户又访问了 http://google.com,然后点击了返回按钮。此时,地址栏将显示 http://mozilla.org/bar.html,同时页面会触发 popstate 事件,事件对象中包含了 stateObj 的一份拷贝。The page itself will look like foo.html, although the page might modify its contents during the popstate event.

If we click back again, the URL will change to http://mozilla.org/foo.html, and the document will get another popstate event, this time with a null state object. Here too, going back doesn't change the document's contents from what they were in the previous step, although the document might update its contents manually upon receiving the popstate event.

pushState() 方法

pushState() 需要三个参数: 一个状态对象, 一个标题 (目前被忽略), 和 (可选的) 一个URL. 让我们来解释下这三个参数详细内容:

  • 状态对象 — 状态对象是一个JavaScript对象,通过pushState () 创建新的历史记录条目。无论什么时候用户导航到新的状态,popstate事件就会被触发,且该事件的state属性包含该历史记录条目状态对象的副本。

    The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.

  • title — Firefox 目前忽略这个参数,但未来可能会用到。Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.

  • URL — 该参数定义了新的历史URL记录。注意,调用 pushState() 后浏览器并不会立即加载这个URL,但可能会在稍后某些情况下加载这个URL,比如在用户重新打开浏览器时。新URL不必须为绝对路径。如果新URL是相对路径,那么它将被作为相对于当前URL处理。新URL必须与当前URL同源,否则 pushState() 会抛出一个异常。该参数是可选的,缺省为当前URL。

Note: 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.

在某种意义上,调用 pushState() 与 设置 window.location = "#foo" 类似,二者都会在当前页面创建并激活新的历史记录。但 pushState() 具有如下几条优点:

  • The new URL can be any URL in the same origin as the current URL. In contrast, setting window.location keeps you at the same 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 #foo.
  • 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.
  • If title is subsequently used by browsers, this data can be utilized (independent of, say, the hash).

Note that pushState() never causes a hashchange event to be fired, even if the new URL differs from the old URL only in its hash.

In a XUL document, it creates the specified XUL element.

In other documents, it creates an element with a null namespace URI.

replaceState() 方法

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one. Note that this doesn't prevent the creation of a new entry in the global browser history.

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.

Note: 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.

replaceState() 方法的例子

Suppose http://mozilla.org/foo.html executes the following JavaScript:

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

The explanation of these two lines above can be found at "Example of pushState() method" section. Then suppose http://mozilla.org/bar.html executes the following JavaScript:

history.replaceState(stateObj, "page 3", "bar2.html");

This will cause the URL bar to display http://mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists.

Suppose now that the user now navigates to http://www.microsoft.com, then clicks back. At this point, the URL bar will display http://mozilla.org/bar2.html. If the user now clicks back again, the URL bar will display http://mozilla.org/foo.html, and totaly bypass bar.html.

popstate 事件

A 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 replaceState, the popstate event's state property contains a copy of the history entry's state object.

See window.onpopstate for sample usage.

获取当前状态

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 pushState() or replaceState()) and then the user restarts their 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.

规范

Specification Status Comment
HTML Living Standard
History
Living Standard No change from HTML5.
HTML5
History
Recommendation Initial definition.

浏览器兼容性

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
replaceState, pushState 5 (Yes) 4.0 (2.0) 10 11.50 5.0
history.state 18 (Yes) 4.0 (2.0) 10 11.50 6.0
Feature Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
replaceState, pushState ? (Yes) ? ? ? ?
history.state ? (Yes) ? ? ? ?

另见

文档标签和贡献者

 此页面的贡献者: LZM, wzx, eightHundreds, keshidong, xgqfrms-GitHub
 最后编辑者: LZM,