修改window.history.state 增加一个属性

Modify window.history.state add a property

我想在 window.history.state 中添加一个名为 html 的 属性,以便以后使用。

所以我做到了:

window.history.state.html = 'something';

但是当我回到历史上时,属性 似乎并不存在。

我尝试了 window.history.replaceState 并复制了所有状态的属性并添加了我需要的属性,但首先它似乎在进行另一个状态推送,这意味着历史上有重复的 url,而且它似乎不太有效出色地。

是否有使用历史记录的解决方案 api 还是我应该创建一个单独的数组并将其 link 到每个推送状态(更复杂)?

根据Mozilla MDN

pushState() takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL.

然后

The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.

所以总而言之,要向history.state对象添加一个属性,你需要将它传递给history.pushState(),你可以通过绑定popstate事件来恢复它.


更新

正如评论中所说,您需要更新您已经推送的状态。正如你所说,

I tried window.history.replaceState and copy all the state's properties and added the one I needed but (...) it doesn't seem to work very well.

我不确定 似乎不太好用 是什么意思,但我很确定这就是您所需要的,所以我会尽力解释它是如何工作的:

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