History:replaceState() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

History 接口的 replaceState() 方法会修改当前历史记录条目,用方法参数中传递的 state 对象和 URL 替换它。当您想在响应某些用户操作时更新当前历史记录条目的 state 对象或 URL 时,此方法特别有用。

语法

js
replaceState(state, unused)
replaceState(state, unused, url)

参数

state

与传递给 replaceState() 方法的历史记录条目关联的对象。state 对象可以为 null

unused

此参数出于历史原因而存在,不可省略;传递空字符串是传统的做法,并且可以保证在未来的方法更改中是安全的。

url 可选

历史记录条目的 URL。新 URL 必须与当前 URL 同源;否则,replaceState() 方法将抛出异常。

返回值

无(undefined)。

异常

SecurityError DOMException

如果关联的文档未完全激活,或者提供的 url 参数不是有效 URL,或者方法调用过于频繁,则会抛出此异常。

DataCloneError DOMException

如果提供的 state 参数不可序列化,则会抛出此异常。

示例

假设 https://www.mozilla.org/foo.html 执行了以下 JavaScript

js
const stateObj = { foo: "bar" };
history.pushState(stateObj, "", "bar.html");

在下一个页面上,您可以使用 history.state 来访问刚刚添加的 stateObj

上述这两行的解释可以在 Working with the History API 文章中找到。然后假设 https://www.mozilla.org/bar.html 执行了以下 JavaScript

js
history.replaceState(stateObj, "", "bar2.html");

这将导致 URL 栏显示 https://www.mozilla.org/bar2.html,但浏览器不会加载 bar2.html,甚至不会检查 bar2.html 是否存在。

现在假设用户导航到 https://www.microsoft.com,然后点击“后退”按钮。此时,URL 栏将显示 https://www.mozilla.org/bar2.html。如果用户现在再次点击“后退”,URL 栏将显示 https://www.mozilla.org/foo.html,并完全跳过 bar.html。

规范

规范
HTML
# dom-history-replacestate-dev

浏览器兼容性