根据Mozilla MDN,
pushState() 采用三个参数:状态对象、标题(当前被忽略)和(可选)URL。
然后
状态对象是一个 JavaScript 对象,它与 pushState() 创建的新历史条目相关联。每当用户导航到新状态时,都会触发一个 popstate 事件,并且该事件的 state 属性包含历史条目的 state 对象的副本。
因此,总而言之,要向history.state 对象添加属性,您需要将其传递给history.pushState(),然后您可以通过绑定popstate 事件来恢复它。
更新
正如 cmets 中所说,您需要更新您已经推送的状态。正如你所说,
我尝试了 window.history.replaceState 并复制了所有状态的属性并添加了我需要的属性,但 (...) 似乎效果不佳。
我不确定似乎不太好用是什么意思,但我很确定这就是你所需要的,所以我将尝试解释它是如何工作的:
0) 在页面加载时,history.state 为空
console.log(history.state);
// Output: null
1) 首先,让我们为popstate 事件设置一个监听器,向我们展示当前状态
window.onpopstate = function(s) { console.log(s.state); }
2) 然后开始推送一些状态
history.pushState({first:1}, document.title);
history.pushState({second:2}, document.title);
history.pushState({third:3}, document.title);
console.log(history.state);
// Output: {third:3}
3) 然后通过添加一个新属性来改变(替换)最后一个状态
var st = history.state;
st.myNewProp = "testing";
history.replaceState(st, document.title);
4) 此时,history.state 已更新
console.log(history.state);
// Output: {third:3, myNewProp: "testing"}
5) 推送你需要的任何其他状态
history.pushState({another:4}, document.title);
6) 然后,用户点击返回按钮,popstate 事件被触发。
// Simulate back button
history.back();
// Output: {third:3, myNewProp: "testing"}
7) 然后,每次返回时,它都会不断弹出状态,直到达到初始 null 状态。
history.back();
// Output: {second:2}
history.back();
// Output: {first:1}
history.back();
// Output: null