History.replaceState()

翻译不完整。 请帮助我们翻译这篇文章!

replaceState()方法使用state objects, title,和 URL 作为参数, 修改当前历史记录实体,如果你想更新当前的state对象或者当前历史实体的URL来响应用户的的动作的话这个方法将会非常有用。

语法

history.replaceState(stateObj, title[, url]);

参数

stateObj
状态对象是一个JavaScript对象,它与传递给 replaceState 方法的历史记录实体相关联.
title
大部分浏览器忽略这个参数, 将来可能有用. 在此处传递空字符串应该可以防止将来对方法的更改。或者,您可以为该状态传递简短标题
url 可选
历史记录实体的URL. 新的URL跟当前的URL必须是同源; 否则 replaceState 抛出一个异常.

例子

假设 http://mozilla.org/foo.html 执行下面的 JavaScript 代码:

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

上面这两行的解释可以在 "Example of pushState() method"这个章节找到。然后假设 http://mozilla.org/bar.html  执行下面的 JavaScript 代码:

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

这会让URL栏显示 http://mozilla.org/bar2.html, 但是不会刷新 bar2.html  页面 甚至不会检查bar2.html 是否存在

假设用户跳转到 http://www.microsoft.com, 然后点击返回按钮.这时, URL 栏将会显示 http://mozilla.org/bar2.html 页面. 如果用户此时点击返回按钮, URL栏将会显示 http://mozilla.org/foo.html 页面, 最终绕过了 bar.html 页面.

说明

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

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
replaceStateChrome Full support 5Edge Full support 12Firefox Full support 4
Notes
Full support 4
Notes
Notes Until Firefox 5, the passed object is serialized using JSON. Starting in Firefox 6, the object is serialized using the structured clone algorithm. This allows a wider variety of objects to be safely passed.
IE Full support 10Opera Full support 11.5Safari Full support 5WebView Android Full support ≤37Chrome Android Full support 18Firefox Android Full support 4
Notes
Full support 4
Notes
Notes Until Firefox 5, the passed object is serialized using JSON. Starting in Firefox 6, the object is serialized using the structured clone algorithm. This allows a wider variety of objects to be safely passed.
Opera Android Full support 11.5Safari iOS Full support 4.3Samsung Internet Android Full support 1.0
Whether the title argument is usedChrome No support NoEdge No support NoFirefox No support NoIE No support NoOpera No support NoSafari Full support YesWebView Android No support NoChrome Android No support NoFirefox Android No support NoOpera Android No support NoSafari iOS ? Samsung Internet Android No support No

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.