history.replaceState() example?

2022-08-30 04:05:57

任何人都可以为history.replaceState举一个工作示例吗?这是 w3.org 说的:

history.replaceState(data, title [, url ] )

更新会话历史记录中的当前条目,使其具有给定的数据、标题以及 URL(如果提供且不为 null)。


更新

这很完美:

history.replaceState( {} , 'foo', '/foo' );

网址正在更改,但标题未更改。这是一个错误还是我错过了什么?在最新的 Chrome 上进行了测试。


答案 1

事实上,这是一个错误,尽管故意的已经2年了。问题在于一些不明确的规格以及涉及后退/前进时的复杂性。document.title

请参阅 WebkitMozilla 上的 bug 参考。此外,Opera在引入History API时表示它没有使用title参数,可能仍然没有。

目前,pushState和replacement的第二个参数 - 历史条目的标题 - 没有在Opera的实现中使用,但可能有一天。

潜在的解决方案

我看到的唯一方法是更改标题元素并改用 pushState:

document.getElementsByTagName('title')[0].innerHTML = 'bar';
window.history.pushState( {} , 'bar', '/bar' );

答案 2

这是一个最小的,人为的例子。

console.log( window.location.href );  // whatever your current location href is
window.history.replaceState( {} , 'foo', '/foo' );
console.log( window.location.href );  // oh, hey, it replaced the path with /foo

还有更多,但我不知道你想用它做什么。replaceState()