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

所以我做了:

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

但是当我回顾历史时,该属性(property)似乎并不存在。

我尝试了 window.history.replaceState 并复制了所有状态的属性并添加了我需要的属性,但首先它似乎在进行另一个状态推送,这意味着历史记录中的重复 url 并且它似乎也不能很好地工作。

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

最佳答案

根据 Mozilla MDN



然后



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

更新

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



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

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

关于javascript - 修改 window.history.state 添加属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32750798/

10-13 02:29