How to add or add a new stateObject to history

I have the following code to save my data in the current state of the page.

 window.history.pushState({myData: data}, "RandomTitle", '#'); 

But now I also want to save another scrollTop value. And if I do

 window.history.pushState({scrollTop: scrollTop}, "RandomTitle", '#'); 

The above code will replace the history state with a new one, and myData will disappear.

Question: Is there a way to add scrollTop , and is there myData in my history state? Or I just need to install it first, like

 window.history.pushState({myData: data, scrollTop: 0}, "RandomTitle", '#'); // To change the scrollTop in history state window.history.state.scrollTop = $(window).scrollTop(); 

I think if there is a function like window.history.state.addObject or something like that.

+5
source share
2 answers

By default, the history.state.addObject function is missing. history.state contains the object you clicked (and nothing more).

You can click on what the addObject method addObject , but that doesn't seem like a good idea. If you want the changes to be transferred to the history as a new state, you must explicitly click the state every time in any case. And when you click on a new state, you want to avoid mutating the previous one, which happens if you use the same state object and change it (even if according to the standard , history.state should be a clone of the actual state data). Instead, you should create a new object (it may be a clone of the previous state).

Here is how you can do it.

 window.history.pushState( Object.assign({}, window.history.state, {scrollTop: scrollTop}), "RandomTitle", '#' ); 

It will work even if there is no current state in the history (i.e. window.history.state is undefined ) as Object.assign ignores undefined .

You can also use this function, which automates it:

 function extendHistoryState(){ arguments[0] = Object.assign({}, window.history.state, arguments[0]); window.history.pushState.apply(window.history, arguments); } 

It works exactly the same as pushState (same arguments), except that it also copies the properties of the previous state in the new state. Therefore, instead of the previous code, you can:

 extendHistoryState({scrollTop: scrollTop}, "RandomTitle", '#'); 
+4
source

Since your URL parameter is the same between pushState methods, you are actually replacing it, not adding a new state to the story. You need to specify a different URL to save state data separately or merge objects and reassign them back to state

0
source

All Articles