修改window.history.state,添加一个属性



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

所以我做了:

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

但是当我回到历史时,属性似乎不在那里。

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

使用历史api是否有解决方案,或者我应该创建一个单独的数组并将其链接到每个pushstate(更复杂)?

根据Mozilla MDN,

pushState()接受三个参数:一个状态对象、一个标题(当前被忽略)和一个URL(可选)。

state对象是一个JavaScript对象,它与pushState()创建的新历史条目相关联。每当用户导航到新状态时,就会触发一个popstate事件,并且该事件的state属性包含历史条目状态对象的副本。

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


更新

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

我尝试了window.history.replaceState并复制所有状态的属性并添加了我需要的属性,但是(…)它似乎工作得不太好。

我不确定似乎不太好是什么意思,但我很确定这是你需要的,所以我会试着解释它是如何工作的:

0)在页面加载时,history.state为null

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);
此时,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

最新更新